<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    
    <title>Custom template tags and filters &mdash; Django 1.7.8.dev20150401230226 documentation</title>
    
    <link rel="stylesheet" href="../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    
    <script type="text/javascript">
      var DOCUMENTATION_OPTIONS = {
        URL_ROOT:    '../',
        VERSION:     '1.7.8.dev20150401230226',
        COLLAPSE_INDEX: false,
        FILE_SUFFIX: '.html',
        HAS_SOURCE:  true
      };
    </script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <link rel="top" title="Django 1.7.8.dev20150401230226 documentation" href="../index.html" />
    <link rel="up" title="“How-to” guides" href="index.html" />
    <link rel="next" title="Writing a custom storage system" href="custom-file-storage.html" />
    <link rel="prev" title="Custom Lookups" href="custom-lookups.html" />



 
<script type="text/javascript" src="../templatebuiltins.js"></script>
<script type="text/javascript">
(function($) {
    if (!django_template_builtins) {
       // templatebuiltins.js missing, do nothing.
       return;
    }
    $(document).ready(function() {
        // Hyperlink Django template tags and filters
        var base = "../ref/templates/builtins.html";
        if (base == "#") {
            // Special case for builtins.html itself
            base = "";
        }
        // Tags are keywords, class '.k'
        $("div.highlight\\-html\\+django span.k").each(function(i, elem) {
             var tagname = $(elem).text();
             if ($.inArray(tagname, django_template_builtins.ttags) != -1) {
                 var fragment = tagname.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + tagname + "</a>");
             }
        });
        // Filters are functions, class '.nf'
        $("div.highlight\\-html\\+django span.nf").each(function(i, elem) {
             var filtername = $(elem).text();
             if ($.inArray(filtername, django_template_builtins.tfilters) != -1) {
                 var fragment = filtername.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + filtername + "</a>");
             }
        });
    });
})(jQuery);
</script>


  </head>
  <body>

    <div class="document">
  <div id="custom-doc" class="yui-t6">
    <div id="hd">
      <h1><a href="../index.html">Django 1.7.8.dev20150401230226 documentation</a></h1>
      <div id="global-nav">
        <a title="Home page" href="../index.html">Home</a>  |
        <a title="Table of contents" href="../contents.html">Table of contents</a>  |
        <a title="Global index" href="../genindex.html">Index</a>  |
        <a title="Module index" href="../py-modindex.html">Modules</a>
      </div>
      <div class="nav">
    &laquo; <a href="custom-lookups.html" title="Custom Lookups">previous</a>
     |
    <a href="index.html" title="&amp;#8220;How-to&amp;#8221; guides" accesskey="U">up</a>
   |
    <a href="custom-file-storage.html" title="Writing a custom storage system">next</a> &raquo;</div>
    </div>

    <div id="bd">
      <div id="yui-main">
        <div class="yui-b">
          <div class="yui-g" id="howto-custom-template-tags">
            
  <div class="section" id="s-custom-template-tags-and-filters">
<span id="custom-template-tags-and-filters"></span><h1>Custom template tags and filters<a class="headerlink" href="#custom-template-tags-and-filters" title="Permalink to this headline">¶</a></h1>
<p>Django&#8217;s template system comes with a wide variety of <a class="reference internal" href="../ref/templates/builtins.html"><em>built-in
tags and filters</em></a> designed to address the
presentation logic needs of your application. Nevertheless, you may
find yourself needing functionality that is not covered by the core
set of template primitives. You can extend the template engine by
defining custom tags and filters using Python, and then make them
available to your templates using the <a class="reference internal" href="../ref/templates/builtins.html#std:templatetag-load"><tt class="xref std std-ttag docutils literal"><span class="pre">{%</span> <span class="pre">load</span> <span class="pre">%}</span></tt></a> tag.</p>
<div class="section" id="s-code-layout">
<span id="code-layout"></span><h2>Code layout<a class="headerlink" href="#code-layout" title="Permalink to this headline">¶</a></h2>
<p>Custom template tags and filters must live inside a Django app. If they relate
to an existing app it makes sense to bundle them there; otherwise, you should
create a new app to hold them.</p>
<p>The app should contain a <tt class="docutils literal"><span class="pre">templatetags</span></tt> directory, at the same level as
<tt class="docutils literal"><span class="pre">models.py</span></tt>, <tt class="docutils literal"><span class="pre">views.py</span></tt>, etc. If this doesn&#8217;t already exist, create it -
don&#8217;t forget the <tt class="docutils literal"><span class="pre">__init__.py</span></tt> file to ensure the directory is treated as a
Python package. After adding this module, you will need to restart your server
before you can use the tags or filters in templates.</p>
<p>Your custom tags and filters will live in a module inside the <tt class="docutils literal"><span class="pre">templatetags</span></tt>
directory. The name of the module file is the name you&#8217;ll use to load the tags
later, so be careful to pick a name that won&#8217;t clash with custom tags and
filters in another app.</p>
<p>For example, if your custom tags/filters are in a file called
<tt class="docutils literal"><span class="pre">poll_extras.py</span></tt>, your app layout might look like this:</p>
<div class="highlight-python"><div class="highlight"><pre>polls/
    __init__.py
    models.py
    templatetags/
        __init__.py
        poll_extras.py
    views.py
</pre></div>
</div>
<p>And in your template you would use the following:</p>
<div class="highlight-html+django"><div class="highlight"><pre><span class="cp">{%</span> <span class="k">load</span> <span class="nv">poll_extras</span> <span class="cp">%}</span>
</pre></div>
</div>
<p>The app that contains the custom tags must be in <a class="reference internal" href="../ref/settings.html#std:setting-INSTALLED_APPS"><tt class="xref std std-setting docutils literal"><span class="pre">INSTALLED_APPS</span></tt></a> in
order for the <a class="reference internal" href="../ref/templates/builtins.html#std:templatetag-load"><tt class="xref std std-ttag docutils literal"><span class="pre">{%</span> <span class="pre">load</span> <span class="pre">%}</span></tt></a> tag to work. This is a security feature:
It allows you to host Python code for many template libraries on a single host
machine without enabling access to all of them for every Django installation.</p>
<p>There&#8217;s no limit on how many modules you put in the <tt class="docutils literal"><span class="pre">templatetags</span></tt> package.
Just keep in mind that a <a class="reference internal" href="../ref/templates/builtins.html#std:templatetag-load"><tt class="xref std std-ttag docutils literal"><span class="pre">{%</span> <span class="pre">load</span> <span class="pre">%}</span></tt></a> statement will load
tags/filters for the given Python module name, not the name of the app.</p>
<p>To be a valid tag library, the module must contain a module-level variable
named <tt class="docutils literal"><span class="pre">register</span></tt> that is a <tt class="docutils literal"><span class="pre">template.Library</span></tt> instance, in which all the
tags and filters are registered. So, near the top of your module, put the
following:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">django</span> <span class="kn">import</span> <span class="n">template</span>

<span class="n">register</span> <span class="o">=</span> <span class="n">template</span><span class="o">.</span><span class="n">Library</span><span class="p">()</span>
</pre></div>
</div>
<div class="admonition-behind-the-scenes admonition">
<p class="first admonition-title">Behind the scenes</p>
<p>For a ton of examples, read the source code for Django&#8217;s default filters
and tags. They&#8217;re in <tt class="docutils literal"><span class="pre">django/template/defaultfilters.py</span></tt> and
<tt class="docutils literal"><span class="pre">django/template/defaulttags.py</span></tt>, respectively.</p>
<p class="last">For more information on the <a class="reference internal" href="../ref/templates/builtins.html#std:templatetag-load"><tt class="xref std std-ttag docutils literal"><span class="pre">load</span></tt></a> tag, read its documentation.</p>
</div>
</div>
<div class="section" id="s-writing-custom-template-filters">
<span id="s-howto-writing-custom-template-filters"></span><span id="writing-custom-template-filters"></span><span id="howto-writing-custom-template-filters"></span><h2>Writing custom template filters<a class="headerlink" href="#writing-custom-template-filters" title="Permalink to this headline">¶</a></h2>
<p>Custom filters are just Python functions that take one or two arguments:</p>
<ul class="simple">
<li>The value of the variable (input) &#8211; not necessarily a string.</li>
<li>The value of the argument &#8211; this can have a default value, or be left
out altogether.</li>
</ul>
<p>For example, in the filter <tt class="docutils literal"><span class="pre">{{</span> <span class="pre">var|foo:&quot;bar&quot;</span> <span class="pre">}}</span></tt>, the filter <tt class="docutils literal"><span class="pre">foo</span></tt> would be
passed the variable <tt class="docutils literal"><span class="pre">var</span></tt> and the argument <tt class="docutils literal"><span class="pre">&quot;bar&quot;</span></tt>.</p>
<p>Usually any exception raised from a template filter will be exposed as a server
error. Thus, filter functions should avoid raising exceptions if there is a
reasonable fallback value to return. In case of input that represents a clear
bug in a template, raising an exception may still be better than silent failure
which hides the bug.</p>
<p>Here&#8217;s an example filter definition:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">cut</span><span class="p">(</span><span class="n">value</span><span class="p">,</span> <span class="n">arg</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;Removes all values of arg from the given string&quot;&quot;&quot;</span>
    <span class="k">return</span> <span class="n">value</span><span class="o">.</span><span class="n">replace</span><span class="p">(</span><span class="n">arg</span><span class="p">,</span> <span class="s">&#39;&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>And here&#8217;s an example of how that filter would be used:</p>
<div class="highlight-html+django"><div class="highlight"><pre><span class="cp">{{</span> <span class="nv">somevariable</span><span class="o">|</span><span class="nf">cut</span><span class="s2">:&quot;0&quot;</span> <span class="cp">}}</span>
</pre></div>
</div>
<p>Most filters don&#8217;t take arguments. In this case, just leave the argument out of
your function. Example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">lower</span><span class="p">(</span><span class="n">value</span><span class="p">):</span> <span class="c"># Only one argument.</span>
    <span class="sd">&quot;&quot;&quot;Converts a string into all lowercase&quot;&quot;&quot;</span>
    <span class="k">return</span> <span class="n">value</span><span class="o">.</span><span class="n">lower</span><span class="p">()</span>
</pre></div>
</div>
<div class="section" id="s-registering-custom-filters">
<span id="registering-custom-filters"></span><h3>Registering custom filters<a class="headerlink" href="#registering-custom-filters" title="Permalink to this headline">¶</a></h3>
<dl class="method">
<dt id="django.template.Library.filter">
<tt class="descclassname">django.template.Library.</tt><tt class="descname">filter</tt>()<a class="headerlink" href="#django.template.Library.filter" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>Once you&#8217;ve written your filter definition, you need to register it with
your <tt class="docutils literal"><span class="pre">Library</span></tt> instance, to make it available to Django&#8217;s template language:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">register</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="s">&#39;cut&#39;</span><span class="p">,</span> <span class="n">cut</span><span class="p">)</span>
<span class="n">register</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="s">&#39;lower&#39;</span><span class="p">,</span> <span class="n">lower</span><span class="p">)</span>
</pre></div>
</div>
<p>The <tt class="docutils literal"><span class="pre">Library.filter()</span></tt> method takes two arguments:</p>
<ol class="arabic simple">
<li>The name of the filter &#8211; a string.</li>
<li>The compilation function &#8211; a Python function (not the name of the
function as a string).</li>
</ol>
<p>You can use <tt class="docutils literal"><span class="pre">register.filter()</span></tt> as a decorator instead:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="nd">@register.filter</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s">&#39;cut&#39;</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">cut</span><span class="p">(</span><span class="n">value</span><span class="p">,</span> <span class="n">arg</span><span class="p">):</span>
    <span class="k">return</span> <span class="n">value</span><span class="o">.</span><span class="n">replace</span><span class="p">(</span><span class="n">arg</span><span class="p">,</span> <span class="s">&#39;&#39;</span><span class="p">)</span>

<span class="nd">@register.filter</span>
<span class="k">def</span> <span class="nf">lower</span><span class="p">(</span><span class="n">value</span><span class="p">):</span>
    <span class="k">return</span> <span class="n">value</span><span class="o">.</span><span class="n">lower</span><span class="p">()</span>
</pre></div>
</div>
<p>If you leave off the <tt class="docutils literal"><span class="pre">name</span></tt> argument, as in the second example above, Django
will use the function&#8217;s name as the filter name.</p>
<p>Finally, <tt class="docutils literal"><span class="pre">register.filter()</span></tt> also accepts three keyword arguments,
<tt class="docutils literal"><span class="pre">is_safe</span></tt>, <tt class="docutils literal"><span class="pre">needs_autoescape</span></tt>, and <tt class="docutils literal"><span class="pre">expects_localtime</span></tt>. These arguments
are described in <a class="reference internal" href="#filters-auto-escaping"><em>filters and auto-escaping</em></a> and
<a class="reference internal" href="#filters-timezones"><em>filters and time zones</em></a> below.</p>
</div>
<div class="section" id="s-template-filters-that-expect-strings">
<span id="template-filters-that-expect-strings"></span><h3>Template filters that expect strings<a class="headerlink" href="#template-filters-that-expect-strings" title="Permalink to this headline">¶</a></h3>
<dl class="method">
<dt id="django.template.defaultfilters.stringfilter">
<tt class="descclassname">django.template.defaultfilters.</tt><tt class="descname">stringfilter</tt>()<a class="headerlink" href="#django.template.defaultfilters.stringfilter" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>If you&#8217;re writing a template filter that only expects a string as the first
argument, you should use the decorator <tt class="docutils literal"><span class="pre">stringfilter</span></tt>. This will
convert an object to its string value before being passed to your function:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">django</span> <span class="kn">import</span> <span class="n">template</span>
<span class="kn">from</span> <span class="nn">django.template.defaultfilters</span> <span class="kn">import</span> <span class="n">stringfilter</span>

<span class="n">register</span> <span class="o">=</span> <span class="n">template</span><span class="o">.</span><span class="n">Library</span><span class="p">()</span>

<span class="nd">@register.filter</span>
<span class="nd">@stringfilter</span>
<span class="k">def</span> <span class="nf">lower</span><span class="p">(</span><span class="n">value</span><span class="p">):</span>
    <span class="k">return</span> <span class="n">value</span><span class="o">.</span><span class="n">lower</span><span class="p">()</span>
</pre></div>
</div>
<p>This way, you&#8217;ll be able to pass, say, an integer to this filter, and it
won&#8217;t cause an <tt class="docutils literal"><span class="pre">AttributeError</span></tt> (because integers don&#8217;t have <tt class="docutils literal"><span class="pre">lower()</span></tt>
methods).</p>
</div>
<div class="section" id="s-filters-and-auto-escaping">
<span id="s-filters-auto-escaping"></span><span id="filters-and-auto-escaping"></span><span id="filters-auto-escaping"></span><h3>Filters and auto-escaping<a class="headerlink" href="#filters-and-auto-escaping" title="Permalink to this headline">¶</a></h3>
<p>When writing a custom filter, give some thought to how the filter will interact
with Django&#8217;s auto-escaping behavior. Note that three types of strings can be
passed around inside the template code:</p>
<ul>
<li><p class="first"><strong>Raw strings</strong> are the native Python <tt class="docutils literal"><span class="pre">str</span></tt> or <tt class="docutils literal"><span class="pre">unicode</span></tt> types. On
output, they&#8217;re escaped if auto-escaping is in effect and presented
unchanged, otherwise.</p>
</li>
<li><p class="first"><strong>Safe strings</strong> are strings that have been marked safe from further
escaping at output time. Any necessary escaping has already been done.
They&#8217;re commonly used for output that contains raw HTML that is intended
to be interpreted as-is on the client side.</p>
<p>Internally, these strings are of type <tt class="docutils literal"><span class="pre">SafeBytes</span></tt> or <tt class="docutils literal"><span class="pre">SafeText</span></tt>.
They share a common base class of <tt class="docutils literal"><span class="pre">SafeData</span></tt>, so you can test
for them using code like:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">value</span><span class="p">,</span> <span class="n">SafeData</span><span class="p">):</span>
    <span class="c"># Do something with the &quot;safe&quot; string.</span>
    <span class="o">...</span>
</pre></div>
</div>
</li>
<li><p class="first"><strong>Strings marked as &#8220;needing escaping&#8221;</strong> are <em>always</em> escaped on
output, regardless of whether they are in an <a class="reference internal" href="../ref/templates/builtins.html#std:templatetag-autoescape"><tt class="xref std std-ttag docutils literal"><span class="pre">autoescape</span></tt></a> block or
not. These strings are only escaped once, however, even if auto-escaping
applies.</p>
<p>Internally, these strings are of type <tt class="docutils literal"><span class="pre">EscapeBytes</span></tt> or
<tt class="docutils literal"><span class="pre">EscapeText</span></tt>. Generally you don&#8217;t have to worry about these; they
exist for the implementation of the <a class="reference internal" href="../ref/templates/builtins.html#std:templatefilter-escape"><tt class="xref std std-tfilter docutils literal"><span class="pre">escape</span></tt></a> filter.</p>
</li>
</ul>
<p>Template filter code falls into one of two situations:</p>
<ol class="arabic">
<li><p class="first">Your filter does not introduce any HTML-unsafe characters (<tt class="docutils literal"><span class="pre">&lt;</span></tt>, <tt class="docutils literal"><span class="pre">&gt;</span></tt>,
<tt class="docutils literal"><span class="pre">'</span></tt>, <tt class="docutils literal"><span class="pre">&quot;</span></tt> or <tt class="docutils literal"><span class="pre">&amp;</span></tt>) into the result that were not already present. In
this case, you can let Django take care of all the auto-escaping
handling for you. All you need to do is set the <tt class="docutils literal"><span class="pre">is_safe</span></tt> flag to <tt class="docutils literal"><span class="pre">True</span></tt>
when you register your filter function, like so:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="nd">@register.filter</span><span class="p">(</span><span class="n">is_safe</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">myfilter</span><span class="p">(</span><span class="n">value</span><span class="p">):</span>
    <span class="k">return</span> <span class="n">value</span>
</pre></div>
</div>
<p>This flag tells Django that if a &#8220;safe&#8221; string is passed into your
filter, the result will still be &#8220;safe&#8221; and if a non-safe string is
passed in, Django will automatically escape it, if necessary.</p>
<p>You can think of this as meaning &#8220;this filter is safe &#8211; it doesn&#8217;t
introduce any possibility of unsafe HTML.&#8221;</p>
<p>The reason <tt class="docutils literal"><span class="pre">is_safe</span></tt> is necessary is because there are plenty of
normal string operations that will turn a <tt class="docutils literal"><span class="pre">SafeData</span></tt> object back into
a normal <tt class="docutils literal"><span class="pre">str</span></tt> or <tt class="docutils literal"><span class="pre">unicode</span></tt> object and, rather than try to catch
them all, which would be very difficult, Django repairs the damage after
the filter has completed.</p>
<p>For example, suppose you have a filter that adds the string <tt class="docutils literal"><span class="pre">xx</span></tt> to
the end of any input. Since this introduces no dangerous HTML characters
to the result (aside from any that were already present), you should
mark your filter with <tt class="docutils literal"><span class="pre">is_safe</span></tt>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="nd">@register.filter</span><span class="p">(</span><span class="n">is_safe</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">add_xx</span><span class="p">(</span><span class="n">value</span><span class="p">):</span>
    <span class="k">return</span> <span class="s">&#39;</span><span class="si">%s</span><span class="s">xx&#39;</span> <span class="o">%</span> <span class="n">value</span>
</pre></div>
</div>
<p>When this filter is used in a template where auto-escaping is enabled,
Django will escape the output whenever the input is not already marked
as &#8220;safe&#8221;.</p>
<p>By default, <tt class="docutils literal"><span class="pre">is_safe</span></tt> is <tt class="docutils literal"><span class="pre">False</span></tt>, and you can omit it from any filters
where it isn&#8217;t required.</p>
<p>Be careful when deciding if your filter really does leave safe strings
as safe. If you&#8217;re <em>removing</em> characters, you might inadvertently leave
unbalanced HTML tags or entities in the result. For example, removing a
<tt class="docutils literal"><span class="pre">&gt;</span></tt> from the input might turn <tt class="docutils literal"><span class="pre">&lt;a&gt;</span></tt> into <tt class="docutils literal"><span class="pre">&lt;a</span></tt>, which would need to
be escaped on output to avoid causing problems. Similarly, removing a
semicolon (<tt class="docutils literal"><span class="pre">;</span></tt>) can turn <tt class="docutils literal"><span class="pre">&amp;amp;</span></tt> into <tt class="docutils literal"><span class="pre">&amp;amp</span></tt>, which is no longer a
valid entity and thus needs further escaping. Most cases won&#8217;t be nearly
this tricky, but keep an eye out for any problems like that when
reviewing your code.</p>
<p>Marking a filter <tt class="docutils literal"><span class="pre">is_safe</span></tt> will coerce the filter&#8217;s return value to
a string.  If your filter should return a boolean or other non-string
value, marking it <tt class="docutils literal"><span class="pre">is_safe</span></tt> will probably have unintended
consequences (such as converting a boolean False to the string
&#8216;False&#8217;).</p>
</li>
<li><p class="first">Alternatively, your filter code can manually take care of any necessary
escaping. This is necessary when you&#8217;re introducing new HTML markup into
the result. You want to mark the output as safe from further
escaping so that your HTML markup isn&#8217;t escaped further, so you&#8217;ll need
to handle the input yourself.</p>
<p>To mark the output as a safe string, use
<a class="reference internal" href="../ref/utils.html#django.utils.safestring.mark_safe" title="django.utils.safestring.mark_safe"><tt class="xref py py-func docutils literal"><span class="pre">django.utils.safestring.mark_safe()</span></tt></a>.</p>
<p>Be careful, though. You need to do more than just mark the output as
safe. You need to ensure it really <em>is</em> safe, and what you do depends on
whether auto-escaping is in effect. The idea is to write filters that
can operate in templates where auto-escaping is either on or off in
order to make things easier for your template authors.</p>
<p>In order for your filter to know the current auto-escaping state, set the
<tt class="docutils literal"><span class="pre">needs_autoescape</span></tt> flag to <tt class="docutils literal"><span class="pre">True</span></tt> when you register your filter function.
(If you don&#8217;t specify this flag, it defaults to <tt class="docutils literal"><span class="pre">False</span></tt>). This flag tells
Django that your filter function wants to be passed an extra keyword
argument, called <tt class="docutils literal"><span class="pre">autoescape</span></tt>, that is <tt class="docutils literal"><span class="pre">True</span></tt> if auto-escaping is in
effect and <tt class="docutils literal"><span class="pre">False</span></tt> otherwise.</p>
<p>For example, let&#8217;s write a filter that emphasizes the first character of
a string:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">django</span> <span class="kn">import</span> <span class="n">template</span>
<span class="kn">from</span> <span class="nn">django.utils.html</span> <span class="kn">import</span> <span class="n">conditional_escape</span>
<span class="kn">from</span> <span class="nn">django.utils.safestring</span> <span class="kn">import</span> <span class="n">mark_safe</span>

<span class="n">register</span> <span class="o">=</span> <span class="n">template</span><span class="o">.</span><span class="n">Library</span><span class="p">()</span>

<span class="nd">@register.filter</span><span class="p">(</span><span class="n">needs_autoescape</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">initial_letter_filter</span><span class="p">(</span><span class="n">text</span><span class="p">,</span> <span class="n">autoescape</span><span class="o">=</span><span class="bp">None</span><span class="p">):</span>
    <span class="n">first</span><span class="p">,</span> <span class="n">other</span> <span class="o">=</span> <span class="n">text</span><span class="p">[</span><span class="mi">0</span><span class="p">],</span> <span class="n">text</span><span class="p">[</span><span class="mi">1</span><span class="p">:]</span>
    <span class="k">if</span> <span class="n">autoescape</span><span class="p">:</span>
        <span class="n">esc</span> <span class="o">=</span> <span class="n">conditional_escape</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="n">esc</span> <span class="o">=</span> <span class="k">lambda</span> <span class="n">x</span><span class="p">:</span> <span class="n">x</span>
    <span class="n">result</span> <span class="o">=</span> <span class="s">&#39;&lt;strong&gt;</span><span class="si">%s</span><span class="s">&lt;/strong&gt;</span><span class="si">%s</span><span class="s">&#39;</span> <span class="o">%</span> <span class="p">(</span><span class="n">esc</span><span class="p">(</span><span class="n">first</span><span class="p">),</span> <span class="n">esc</span><span class="p">(</span><span class="n">other</span><span class="p">))</span>
    <span class="k">return</span> <span class="n">mark_safe</span><span class="p">(</span><span class="n">result</span><span class="p">)</span>
</pre></div>
</div>
<p>The <tt class="docutils literal"><span class="pre">needs_autoescape</span></tt> flag and the <tt class="docutils literal"><span class="pre">autoescape</span></tt> keyword argument mean
that our function will know whether automatic escaping is in effect when the
filter is called. We use <tt class="docutils literal"><span class="pre">autoescape</span></tt> to decide whether the input data
needs to be passed through <tt class="docutils literal"><span class="pre">django.utils.html.conditional_escape</span></tt> or not.
(In the latter case, we just use the identity function as the &#8220;escape&#8221;
function.) The <tt class="docutils literal"><span class="pre">conditional_escape()</span></tt> function is like <tt class="docutils literal"><span class="pre">escape()</span></tt> except
it only escapes input that is <strong>not</strong> a <tt class="docutils literal"><span class="pre">SafeData</span></tt> instance. If a
<tt class="docutils literal"><span class="pre">SafeData</span></tt> instance is passed to <tt class="docutils literal"><span class="pre">conditional_escape()</span></tt>, the data is
returned unchanged.</p>
<p>Finally, in the above example, we remember to mark the result as safe
so that our HTML is inserted directly into the template without further
escaping.</p>
<p>There&#8217;s no need to worry about the <tt class="docutils literal"><span class="pre">is_safe</span></tt> flag in this case
(although including it wouldn&#8217;t hurt anything). Whenever you manually
handle the auto-escaping issues and return a safe string, the
<tt class="docutils literal"><span class="pre">is_safe</span></tt> flag won&#8217;t change anything either way.</p>
</li>
</ol>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p>Avoiding XSS vulnerabilities when reusing built-in filters</p>
<p>Be careful when reusing Django&#8217;s built-in filters. You&#8217;ll need to pass
<tt class="docutils literal"><span class="pre">autoescape=True</span></tt> to the filter in order to get the proper autoescaping
behavior and avoid a cross-site script vulnerability.</p>
<p>For example, if you wanted to write a custom filter called
<tt class="docutils literal"><span class="pre">urlize_and_linebreaks</span></tt> that combined the <a class="reference internal" href="../ref/templates/builtins.html#std:templatefilter-urlize"><tt class="xref std std-tfilter docutils literal"><span class="pre">urlize</span></tt></a> and
<a class="reference internal" href="../ref/templates/builtins.html#std:templatefilter-linebreaksbr"><tt class="xref std std-tfilter docutils literal"><span class="pre">linebreaksbr</span></tt></a> filters, the filter would look like:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">django.template.defaultfilters</span> <span class="kn">import</span> <span class="n">linebreaksbr</span><span class="p">,</span> <span class="n">urlize</span>

<span class="nd">@register.filter</span>
<span class="k">def</span> <span class="nf">urlize_and_linebreaks</span><span class="p">(</span><span class="n">text</span><span class="p">):</span>
    <span class="k">return</span> <span class="n">linebreaksbr</span><span class="p">(</span><span class="n">urlize</span><span class="p">(</span><span class="n">text</span><span class="p">,</span> <span class="n">autoescape</span><span class="o">=</span><span class="bp">True</span><span class="p">),</span> <span class="n">autoescape</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
</pre></div>
</div>
<p>Then:</p>
<div class="highlight-html+django"><div class="highlight"><pre><span class="cp">{{</span> <span class="nv">comment</span><span class="o">|</span><span class="nf">urlize_and_linebreaks</span> <span class="cp">}}</span>
</pre></div>
</div>
<p>would be equivalent to:</p>
<div class="last highlight-html+django"><div class="highlight"><pre><span class="cp">{{</span> <span class="nv">comment</span><span class="o">|</span><span class="nf">urlize</span><span class="o">|</span><span class="nf">linebreaksbr</span> <span class="cp">}}</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="s-filters-and-time-zones">
<span id="s-filters-timezones"></span><span id="filters-and-time-zones"></span><span id="filters-timezones"></span><h3>Filters and time zones<a class="headerlink" href="#filters-and-time-zones" title="Permalink to this headline">¶</a></h3>
<p>If you write a custom filter that operates on <a class="reference external" href="http://docs.python.org/3/library/datetime.html#datetime.datetime" title="(in Python v3.4)"><tt class="xref py py-class docutils literal"><span class="pre">datetime</span></tt></a>
objects, you&#8217;ll usually register it with the <tt class="docutils literal"><span class="pre">expects_localtime</span></tt> flag set to
<tt class="docutils literal"><span class="pre">True</span></tt>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="nd">@register.filter</span><span class="p">(</span><span class="n">expects_localtime</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">businesshours</span><span class="p">(</span><span class="n">value</span><span class="p">):</span>
    <span class="k">try</span><span class="p">:</span>
        <span class="k">return</span> <span class="mi">9</span> <span class="o">&lt;=</span> <span class="n">value</span><span class="o">.</span><span class="n">hour</span> <span class="o">&lt;</span> <span class="mi">17</span>
    <span class="k">except</span> <span class="ne">AttributeError</span><span class="p">:</span>
        <span class="k">return</span> <span class="s">&#39;&#39;</span>
</pre></div>
</div>
<p>When this flag is set, if the first argument to your filter is a time zone
aware datetime, Django will convert it to the current time zone before passing
it to your filter when appropriate, according to <a class="reference internal" href="../topics/i18n/timezones.html#time-zones-in-templates"><em>rules for time zones
conversions in templates</em></a>.</p>
</div>
</div>
<div class="section" id="s-writing-custom-template-tags">
<span id="writing-custom-template-tags"></span><h2>Writing custom template tags<a class="headerlink" href="#writing-custom-template-tags" title="Permalink to this headline">¶</a></h2>
<p>Tags are more complex than filters, because tags can do anything.</p>
<div class="section" id="s-a-quick-overview">
<span id="a-quick-overview"></span><h3>A quick overview<a class="headerlink" href="#a-quick-overview" title="Permalink to this headline">¶</a></h3>
<p>Above, this document explained that the template system works in a two-step
process: compiling and rendering. To define a custom template tag, you specify
how the compilation works and how the rendering works.</p>
<p>When Django compiles a template, it splits the raw template text into
&#8216;&#8217;nodes&#8217;&#8216;. Each node is an instance of <tt class="docutils literal"><span class="pre">django.template.Node</span></tt> and has
a <tt class="docutils literal"><span class="pre">render()</span></tt> method. A compiled template is, simply, a list of <tt class="docutils literal"><span class="pre">Node</span></tt>
objects. When you call <tt class="docutils literal"><span class="pre">render()</span></tt> on a compiled template object, the template
calls <tt class="docutils literal"><span class="pre">render()</span></tt> on each <tt class="docutils literal"><span class="pre">Node</span></tt> in its node list, with the given context.
The results are all concatenated together to form the output of the template.</p>
<p>Thus, to define a custom template tag, you specify how the raw template tag is
converted into a <tt class="docutils literal"><span class="pre">Node</span></tt> (the compilation function), and what the node&#8217;s
<tt class="docutils literal"><span class="pre">render()</span></tt> method does.</p>
</div>
<div class="section" id="s-writing-the-compilation-function">
<span id="writing-the-compilation-function"></span><h3>Writing the compilation function<a class="headerlink" href="#writing-the-compilation-function" title="Permalink to this headline">¶</a></h3>
<p>For each template tag the template parser encounters, it calls a Python
function with the tag contents and the parser object itself. This function is
responsible for returning a <tt class="docutils literal"><span class="pre">Node</span></tt> instance based on the contents of the tag.</p>
<p>For example, let&#8217;s write a template tag, <tt class="docutils literal"><span class="pre">{%</span> <span class="pre">current_time</span> <span class="pre">%}</span></tt>, that displays
the current date/time, formatted according to a parameter given in the tag, in
<a class="reference external" href="http://docs.python.org/3/library/time.html#time.strftime" title="(in Python v3.4)"><tt class="xref py py-func docutils literal"><span class="pre">strftime()</span></tt></a> syntax. It&#8217;s a good idea to decide the tag syntax before
anything else. In our case, let&#8217;s say the tag should be used like this:</p>
<div class="highlight-html+django"><div class="highlight"><pre><span class="nt">&lt;p&gt;</span>The time is <span class="cp">{%</span> <span class="k">current_time</span> <span class="s2">&quot;%Y-%m-%d %I:%M %p&quot;</span> <span class="cp">%}</span>.<span class="nt">&lt;/p&gt;</span>
</pre></div>
</div>
<p>The parser for this function should grab the parameter and create a <tt class="docutils literal"><span class="pre">Node</span></tt>
object:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">django</span> <span class="kn">import</span> <span class="n">template</span>
<span class="k">def</span> <span class="nf">do_current_time</span><span class="p">(</span><span class="n">parser</span><span class="p">,</span> <span class="n">token</span><span class="p">):</span>
    <span class="k">try</span><span class="p">:</span>
        <span class="c"># split_contents() knows not to split quoted strings.</span>
        <span class="n">tag_name</span><span class="p">,</span> <span class="n">format_string</span> <span class="o">=</span> <span class="n">token</span><span class="o">.</span><span class="n">split_contents</span><span class="p">()</span>
    <span class="k">except</span> <span class="ne">ValueError</span><span class="p">:</span>
        <span class="k">raise</span> <span class="n">template</span><span class="o">.</span><span class="n">TemplateSyntaxError</span><span class="p">(</span>
            <span class="s">&quot;</span><span class="si">%r</span><span class="s"> tag requires a single argument&quot;</span> <span class="o">%</span> <span class="n">token</span><span class="o">.</span><span class="n">contents</span><span class="o">.</span><span class="n">split</span><span class="p">()[</span><span class="mi">0</span><span class="p">]</span>
        <span class="p">)</span>
    <span class="k">if</span> <span class="ow">not</span> <span class="p">(</span><span class="n">format_string</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">==</span> <span class="n">format_string</span><span class="p">[</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span> <span class="ow">and</span> <span class="n">format_string</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="ow">in</span> <span class="p">(</span><span class="s">&#39;&quot;&#39;</span><span class="p">,</span> <span class="s">&quot;&#39;&quot;</span><span class="p">)):</span>
        <span class="k">raise</span> <span class="n">template</span><span class="o">.</span><span class="n">TemplateSyntaxError</span><span class="p">(</span>
            <span class="s">&quot;</span><span class="si">%r</span><span class="s"> tag&#39;s argument should be in quotes&quot;</span> <span class="o">%</span> <span class="n">tag_name</span>
        <span class="p">)</span>
    <span class="k">return</span> <span class="n">CurrentTimeNode</span><span class="p">(</span><span class="n">format_string</span><span class="p">[</span><span class="mi">1</span><span class="p">:</span><span class="o">-</span><span class="mi">1</span><span class="p">])</span>
</pre></div>
</div>
<p>Notes:</p>
<ul class="simple">
<li><tt class="docutils literal"><span class="pre">parser</span></tt> is the template parser object. We don&#8217;t need it in this
example.</li>
<li><tt class="docutils literal"><span class="pre">token.contents</span></tt> is a string of the raw contents of the tag. In our
example, it&#8217;s <tt class="docutils literal"><span class="pre">'current_time</span> <span class="pre">&quot;%Y-%m-%d</span> <span class="pre">%I:%M</span> <span class="pre">%p&quot;'</span></tt>.</li>
<li>The <tt class="docutils literal"><span class="pre">token.split_contents()</span></tt> method separates the arguments on spaces
while keeping quoted strings together. The more straightforward
<tt class="docutils literal"><span class="pre">token.contents.split()</span></tt> wouldn&#8217;t be as robust, as it would naively
split on <em>all</em> spaces, including those within quoted strings. It&#8217;s a good
idea to always use <tt class="docutils literal"><span class="pre">token.split_contents()</span></tt>.</li>
<li>This function is responsible for raising
<tt class="docutils literal"><span class="pre">django.template.TemplateSyntaxError</span></tt>, with helpful messages, for
any syntax error.</li>
<li>The <tt class="docutils literal"><span class="pre">TemplateSyntaxError</span></tt> exceptions use the <tt class="docutils literal"><span class="pre">tag_name</span></tt> variable.
Don&#8217;t hard-code the tag&#8217;s name in your error messages, because that
couples the tag&#8217;s name to your function. <tt class="docutils literal"><span class="pre">token.contents.split()[0]</span></tt>
will &#8216;&#8217;always&#8217;&#8217; be the name of your tag &#8211; even when the tag has no
arguments.</li>
<li>The function returns a <tt class="docutils literal"><span class="pre">CurrentTimeNode</span></tt> with everything the node needs
to know about this tag. In this case, it just passes the argument &#8211;
<tt class="docutils literal"><span class="pre">&quot;%Y-%m-%d</span> <span class="pre">%I:%M</span> <span class="pre">%p&quot;</span></tt>. The leading and trailing quotes from the
template tag are removed in <tt class="docutils literal"><span class="pre">format_string[1:-1]</span></tt>.</li>
<li>The parsing is very low-level. The Django developers have experimented
with writing small frameworks on top of this parsing system, using
techniques such as EBNF grammars, but those experiments made the template
engine too slow. It&#8217;s low-level because that&#8217;s fastest.</li>
</ul>
</div>
<div class="section" id="s-writing-the-renderer">
<span id="writing-the-renderer"></span><h3>Writing the renderer<a class="headerlink" href="#writing-the-renderer" title="Permalink to this headline">¶</a></h3>
<p>The second step in writing custom tags is to define a <tt class="docutils literal"><span class="pre">Node</span></tt> subclass that
has a <tt class="docutils literal"><span class="pre">render()</span></tt> method.</p>
<p>Continuing the above example, we need to define <tt class="docutils literal"><span class="pre">CurrentTimeNode</span></tt>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">datetime</span>
<span class="kn">from</span> <span class="nn">django</span> <span class="kn">import</span> <span class="n">template</span>

<span class="k">class</span> <span class="nc">CurrentTimeNode</span><span class="p">(</span><span class="n">template</span><span class="o">.</span><span class="n">Node</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">format_string</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">format_string</span> <span class="o">=</span> <span class="n">format_string</span>
    <span class="k">def</span> <span class="nf">render</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">context</span><span class="p">):</span>
        <span class="k">return</span> <span class="n">datetime</span><span class="o">.</span><span class="n">datetime</span><span class="o">.</span><span class="n">now</span><span class="p">()</span><span class="o">.</span><span class="n">strftime</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">format_string</span><span class="p">)</span>
</pre></div>
</div>
<p>Notes:</p>
<ul class="simple">
<li><tt class="docutils literal"><span class="pre">__init__()</span></tt> gets the <tt class="docutils literal"><span class="pre">format_string</span></tt> from <tt class="docutils literal"><span class="pre">do_current_time()</span></tt>.
Always pass any options/parameters/arguments to a <tt class="docutils literal"><span class="pre">Node</span></tt> via its
<tt class="docutils literal"><span class="pre">__init__()</span></tt>.</li>
<li>The <tt class="docutils literal"><span class="pre">render()</span></tt> method is where the work actually happens.</li>
<li><tt class="docutils literal"><span class="pre">render()</span></tt> should generally fail silently, particularly in a production
environment where <a class="reference internal" href="../ref/settings.html#std:setting-DEBUG"><tt class="xref std std-setting docutils literal"><span class="pre">DEBUG</span></tt></a> and <a class="reference internal" href="../ref/settings.html#std:setting-TEMPLATE_DEBUG"><tt class="xref std std-setting docutils literal"><span class="pre">TEMPLATE_DEBUG</span></tt></a> are
<tt class="docutils literal"><span class="pre">False</span></tt>. In some cases however, particularly if <a class="reference internal" href="../ref/settings.html#std:setting-TEMPLATE_DEBUG"><tt class="xref std std-setting docutils literal"><span class="pre">TEMPLATE_DEBUG</span></tt></a> is
<tt class="docutils literal"><span class="pre">True</span></tt>, this method may raise an exception to make debugging easier. For
example, several core tags raise <tt class="docutils literal"><span class="pre">django.template.TemplateSyntaxError</span></tt>
if they receive the wrong number or type of arguments.</li>
</ul>
<p>Ultimately, this decoupling of compilation and rendering results in an
efficient template system, because a template can render multiple contexts
without having to be parsed multiple times.</p>
</div>
<div class="section" id="s-auto-escaping-considerations">
<span id="auto-escaping-considerations"></span><h3>Auto-escaping considerations<a class="headerlink" href="#auto-escaping-considerations" title="Permalink to this headline">¶</a></h3>
<p>The output from template tags is <strong>not</strong> automatically run through the
auto-escaping filters. However, there are still a couple of things you should
keep in mind when writing a template tag.</p>
<p>If the <tt class="docutils literal"><span class="pre">render()</span></tt> function of your template stores the result in a context
variable (rather than returning the result in a string), it should take care
to call <tt class="docutils literal"><span class="pre">mark_safe()</span></tt> if appropriate. When the variable is ultimately
rendered, it will be affected by the auto-escape setting in effect at the
time, so content that should be safe from further escaping needs to be marked
as such.</p>
<p>Also, if your template tag creates a new context for performing some
sub-rendering, set the auto-escape attribute to the current context&#8217;s value.
The <tt class="docutils literal"><span class="pre">__init__</span></tt> method for the <tt class="docutils literal"><span class="pre">Context</span></tt> class takes a parameter called
<tt class="docutils literal"><span class="pre">autoescape</span></tt> that you can use for this purpose. For example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">django.template</span> <span class="kn">import</span> <span class="n">Context</span>

<span class="k">def</span> <span class="nf">render</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">context</span><span class="p">):</span>
    <span class="c"># ...</span>
    <span class="n">new_context</span> <span class="o">=</span> <span class="n">Context</span><span class="p">({</span><span class="s">&#39;var&#39;</span><span class="p">:</span> <span class="n">obj</span><span class="p">},</span> <span class="n">autoescape</span><span class="o">=</span><span class="n">context</span><span class="o">.</span><span class="n">autoescape</span><span class="p">)</span>
    <span class="c"># ... Do something with new_context ...</span>
</pre></div>
</div>
<p>This is not a very common situation, but it&#8217;s useful if you&#8217;re rendering a
template yourself. For example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">render</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">context</span><span class="p">):</span>
    <span class="n">t</span> <span class="o">=</span> <span class="n">template</span><span class="o">.</span><span class="n">loader</span><span class="o">.</span><span class="n">get_template</span><span class="p">(</span><span class="s">&#39;small_fragment.html&#39;</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">t</span><span class="o">.</span><span class="n">render</span><span class="p">(</span><span class="n">Context</span><span class="p">({</span><span class="s">&#39;var&#39;</span><span class="p">:</span> <span class="n">obj</span><span class="p">},</span> <span class="n">autoescape</span><span class="o">=</span><span class="n">context</span><span class="o">.</span><span class="n">autoescape</span><span class="p">))</span>
</pre></div>
</div>
<p>If we had neglected to pass in the current <tt class="docutils literal"><span class="pre">context.autoescape</span></tt> value to our
new <tt class="docutils literal"><span class="pre">Context</span></tt> in this example, the results would have <em>always</em> been
automatically escaped, which may not be the desired behavior if the template
tag is used inside a <a class="reference internal" href="../ref/templates/builtins.html#std:templatetag-autoescape"><tt class="xref std std-ttag docutils literal"><span class="pre">{%</span> <span class="pre">autoescape</span> <span class="pre">off</span> <span class="pre">%}</span></tt></a> block.</p>
</div>
<div class="section" id="s-thread-safety-considerations">
<span id="s-template-tag-thread-safety"></span><span id="thread-safety-considerations"></span><span id="template-tag-thread-safety"></span><h3>Thread-safety considerations<a class="headerlink" href="#thread-safety-considerations" title="Permalink to this headline">¶</a></h3>
<p>Once a node is parsed, its <tt class="docutils literal"><span class="pre">render</span></tt> method may be called any number of times.
Since Django is sometimes run in multi-threaded environments, a single node may
be simultaneously rendering with different contexts in response to two separate
requests. Therefore, it&#8217;s important to make sure your template tags are thread
safe.</p>
<p>To make sure your template tags are thread safe, you should never store state
information on the node itself. For example, Django provides a builtin
<a class="reference internal" href="../ref/templates/builtins.html#std:templatetag-cycle"><tt class="xref std std-ttag docutils literal"><span class="pre">cycle</span></tt></a> template tag that cycles among a list of given strings each time
it&#8217;s rendered:</p>
<div class="highlight-html+django"><div class="highlight"><pre><span class="cp">{%</span> <span class="k">for</span> <span class="nv">o</span> <span class="k">in</span> <span class="nv">some_list</span> <span class="cp">%}</span>
    <span class="nt">&lt;tr</span> <span class="na">class=</span><span class="s">&quot;</span><span class="cp">{%</span> <span class="k">cycle</span> <span class="s1">&#39;row1&#39;</span> <span class="s1">&#39;row2&#39;</span> <span class="cp">%}</span><span class="s">&quot;</span><span class="nt">&gt;</span>
        ...
    <span class="nt">&lt;/tr&gt;</span>
<span class="cp">{%</span> <span class="k">endfor</span> <span class="cp">%}</span>
</pre></div>
</div>
<p>A naive implementation of <tt class="docutils literal"><span class="pre">CycleNode</span></tt> might look something like this:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">itertools</span>
<span class="kn">from</span> <span class="nn">django</span> <span class="kn">import</span> <span class="n">template</span>

<span class="k">class</span> <span class="nc">CycleNode</span><span class="p">(</span><span class="n">template</span><span class="o">.</span><span class="n">Node</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">cyclevars</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">cycle_iter</span> <span class="o">=</span> <span class="n">itertools</span><span class="o">.</span><span class="n">cycle</span><span class="p">(</span><span class="n">cyclevars</span><span class="p">)</span>
    <span class="k">def</span> <span class="nf">render</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">context</span><span class="p">):</span>
        <span class="k">return</span> <span class="nb">next</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">cycle_iter</span><span class="p">)</span>
</pre></div>
</div>
<p>But, suppose we have two templates rendering the template snippet from above at
the same time:</p>
<ol class="arabic simple">
<li>Thread 1 performs its first loop iteration, <tt class="docutils literal"><span class="pre">CycleNode.render()</span></tt>
returns &#8216;row1&#8217;</li>
<li>Thread 2 performs its first loop iteration, <tt class="docutils literal"><span class="pre">CycleNode.render()</span></tt>
returns &#8216;row2&#8217;</li>
<li>Thread 1 performs its second loop iteration, <tt class="docutils literal"><span class="pre">CycleNode.render()</span></tt>
returns &#8216;row1&#8217;</li>
<li>Thread 2 performs its second loop iteration, <tt class="docutils literal"><span class="pre">CycleNode.render()</span></tt>
returns &#8216;row2&#8217;</li>
</ol>
<p>The CycleNode is iterating, but it&#8217;s iterating globally. As far as Thread 1
and Thread 2 are concerned, it&#8217;s always returning the same value. This is
obviously not what we want!</p>
<p>To address this problem, Django provides a <tt class="docutils literal"><span class="pre">render_context</span></tt> that&#8217;s associated
with the <tt class="docutils literal"><span class="pre">context</span></tt> of the template that is currently being rendered. The
<tt class="docutils literal"><span class="pre">render_context</span></tt> behaves like a Python dictionary, and should be used to
store <tt class="docutils literal"><span class="pre">Node</span></tt> state between invocations of the <tt class="docutils literal"><span class="pre">render</span></tt> method.</p>
<p>Let&#8217;s refactor our <tt class="docutils literal"><span class="pre">CycleNode</span></tt> implementation to use the <tt class="docutils literal"><span class="pre">render_context</span></tt>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">CycleNode</span><span class="p">(</span><span class="n">template</span><span class="o">.</span><span class="n">Node</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">cyclevars</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">cyclevars</span> <span class="o">=</span> <span class="n">cyclevars</span>
    <span class="k">def</span> <span class="nf">render</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">context</span><span class="p">):</span>
        <span class="k">if</span> <span class="bp">self</span> <span class="ow">not</span> <span class="ow">in</span> <span class="n">context</span><span class="o">.</span><span class="n">render_context</span><span class="p">:</span>
            <span class="n">context</span><span class="o">.</span><span class="n">render_context</span><span class="p">[</span><span class="bp">self</span><span class="p">]</span> <span class="o">=</span> <span class="n">itertools</span><span class="o">.</span><span class="n">cycle</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">cyclevars</span><span class="p">)</span>
        <span class="n">cycle_iter</span> <span class="o">=</span> <span class="n">context</span><span class="o">.</span><span class="n">render_context</span><span class="p">[</span><span class="bp">self</span><span class="p">]</span>
        <span class="k">return</span> <span class="nb">next</span><span class="p">(</span><span class="n">cycle_iter</span><span class="p">)</span>
</pre></div>
</div>
<p>Note that it&#8217;s perfectly safe to store global information that will not change
throughout the life of the <tt class="docutils literal"><span class="pre">Node</span></tt> as an attribute. In the case of
<tt class="docutils literal"><span class="pre">CycleNode</span></tt>, the <tt class="docutils literal"><span class="pre">cyclevars</span></tt> argument doesn&#8217;t change after the <tt class="docutils literal"><span class="pre">Node</span></tt> is
instantiated, so we don&#8217;t need to put it in the <tt class="docutils literal"><span class="pre">render_context</span></tt>. But state
information that is specific to the template that is currently being rendered,
like the current iteration of the <tt class="docutils literal"><span class="pre">CycleNode</span></tt>, should be stored in the
<tt class="docutils literal"><span class="pre">render_context</span></tt>.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Notice how we used <tt class="docutils literal"><span class="pre">self</span></tt> to scope the <tt class="docutils literal"><span class="pre">CycleNode</span></tt> specific information
within the <tt class="docutils literal"><span class="pre">render_context</span></tt>. There may be multiple <tt class="docutils literal"><span class="pre">CycleNodes</span></tt> in a
given template, so we need to be careful not to clobber another node&#8217;s
state information. The easiest way to do this is to always use <tt class="docutils literal"><span class="pre">self</span></tt> as
the key into <tt class="docutils literal"><span class="pre">render_context</span></tt>. If you&#8217;re keeping track of several state
variables, make <tt class="docutils literal"><span class="pre">render_context[self]</span></tt> a dictionary.</p>
</div>
</div>
<div class="section" id="s-registering-the-tag">
<span id="registering-the-tag"></span><h3>Registering the tag<a class="headerlink" href="#registering-the-tag" title="Permalink to this headline">¶</a></h3>
<p>Finally, register the tag with your module&#8217;s <tt class="docutils literal"><span class="pre">Library</span></tt> instance, as explained
in &#8220;Writing custom template filters&#8221; above. Example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">register</span><span class="o">.</span><span class="n">tag</span><span class="p">(</span><span class="s">&#39;current_time&#39;</span><span class="p">,</span> <span class="n">do_current_time</span><span class="p">)</span>
</pre></div>
</div>
<p>The <tt class="docutils literal"><span class="pre">tag()</span></tt> method takes two arguments:</p>
<ol class="arabic simple">
<li>The name of the template tag &#8211; a string. If this is left out, the
name of the compilation function will be used.</li>
<li>The compilation function &#8211; a Python function (not the name of the
function as a string).</li>
</ol>
<p>As with filter registration, it is also possible to use this as a decorator:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="nd">@register.tag</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s">&quot;current_time&quot;</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">do_current_time</span><span class="p">(</span><span class="n">parser</span><span class="p">,</span> <span class="n">token</span><span class="p">):</span>
    <span class="o">...</span>

<span class="nd">@register.tag</span>
<span class="k">def</span> <span class="nf">shout</span><span class="p">(</span><span class="n">parser</span><span class="p">,</span> <span class="n">token</span><span class="p">):</span>
    <span class="o">...</span>
</pre></div>
</div>
<p>If you leave off the <tt class="docutils literal"><span class="pre">name</span></tt> argument, as in the second example above, Django
will use the function&#8217;s name as the tag name.</p>
</div>
<div class="section" id="s-passing-template-variables-to-the-tag">
<span id="passing-template-variables-to-the-tag"></span><h3>Passing template variables to the tag<a class="headerlink" href="#passing-template-variables-to-the-tag" title="Permalink to this headline">¶</a></h3>
<p>Although you can pass any number of arguments to a template tag using
<tt class="docutils literal"><span class="pre">token.split_contents()</span></tt>, the arguments are all unpacked as
string literals. A little more work is required in order to pass dynamic
content (a template variable) to a template tag as an argument.</p>
<p>While the previous examples have formatted the current time into a string and
returned the string, suppose you wanted to pass in a
<a class="reference internal" href="../ref/models/fields.html#django.db.models.DateTimeField" title="django.db.models.DateTimeField"><tt class="xref py py-class docutils literal"><span class="pre">DateTimeField</span></tt></a> from an object and have the template
tag format that date-time:</p>
<div class="highlight-html+django"><div class="highlight"><pre><span class="nt">&lt;p&gt;</span>This post was last updated at <span class="cp">{%</span> <span class="k">format_time</span> <span class="nv">blog_entry.date_updated</span> <span class="s2">&quot;%Y-%m-%d %I:%M %p&quot;</span> <span class="cp">%}</span>.<span class="nt">&lt;/p&gt;</span>
</pre></div>
</div>
<p>Initially, <tt class="docutils literal"><span class="pre">token.split_contents()</span></tt> will return three values:</p>
<ol class="arabic simple">
<li>The tag name <tt class="docutils literal"><span class="pre">format_time</span></tt>.</li>
<li>The string <tt class="docutils literal"><span class="pre">&quot;blog_entry.date_updated&quot;</span></tt> (without the surrounding
quotes).</li>
<li>The formatting string <tt class="docutils literal"><span class="pre">&quot;%Y-%m-%d</span> <span class="pre">%I:%M</span> <span class="pre">%p&quot;</span></tt>. The return value from
<tt class="docutils literal"><span class="pre">split_contents()</span></tt> will include the leading and trailing quotes for
string literals like this.</li>
</ol>
<p>Now your tag should begin to look like this:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">django</span> <span class="kn">import</span> <span class="n">template</span>

<span class="k">def</span> <span class="nf">do_format_time</span><span class="p">(</span><span class="n">parser</span><span class="p">,</span> <span class="n">token</span><span class="p">):</span>
    <span class="k">try</span><span class="p">:</span>
        <span class="c"># split_contents() knows not to split quoted strings.</span>
        <span class="n">tag_name</span><span class="p">,</span> <span class="n">date_to_be_formatted</span><span class="p">,</span> <span class="n">format_string</span> <span class="o">=</span> <span class="n">token</span><span class="o">.</span><span class="n">split_contents</span><span class="p">()</span>
    <span class="k">except</span> <span class="ne">ValueError</span><span class="p">:</span>
        <span class="k">raise</span> <span class="n">template</span><span class="o">.</span><span class="n">TemplateSyntaxError</span><span class="p">(</span>
            <span class="s">&quot;</span><span class="si">%r</span><span class="s"> tag requires exactly two arguments&quot;</span> <span class="o">%</span> <span class="n">token</span><span class="o">.</span><span class="n">contents</span><span class="o">.</span><span class="n">split</span><span class="p">()[</span><span class="mi">0</span><span class="p">]</span>
        <span class="p">)</span>
    <span class="k">if</span> <span class="ow">not</span> <span class="p">(</span><span class="n">format_string</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">==</span> <span class="n">format_string</span><span class="p">[</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span> <span class="ow">and</span> <span class="n">format_string</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="ow">in</span> <span class="p">(</span><span class="s">&#39;&quot;&#39;</span><span class="p">,</span> <span class="s">&quot;&#39;&quot;</span><span class="p">)):</span>
        <span class="k">raise</span> <span class="n">template</span><span class="o">.</span><span class="n">TemplateSyntaxError</span><span class="p">(</span>
            <span class="s">&quot;</span><span class="si">%r</span><span class="s"> tag&#39;s argument should be in quotes&quot;</span> <span class="o">%</span> <span class="n">tag_name</span>
        <span class="p">)</span>
    <span class="k">return</span> <span class="n">FormatTimeNode</span><span class="p">(</span><span class="n">date_to_be_formatted</span><span class="p">,</span> <span class="n">format_string</span><span class="p">[</span><span class="mi">1</span><span class="p">:</span><span class="o">-</span><span class="mi">1</span><span class="p">])</span>
</pre></div>
</div>
<p>You also have to change the renderer to retrieve the actual contents of the
<tt class="docutils literal"><span class="pre">date_updated</span></tt> property of the <tt class="docutils literal"><span class="pre">blog_entry</span></tt> object.  This can be
accomplished by using the <tt class="docutils literal"><span class="pre">Variable()</span></tt> class in <tt class="docutils literal"><span class="pre">django.template</span></tt>.</p>
<p>To use the <tt class="docutils literal"><span class="pre">Variable</span></tt> class, simply instantiate it with the name of the
variable to be resolved, and then call <tt class="docutils literal"><span class="pre">variable.resolve(context)</span></tt>. So,
for example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">FormatTimeNode</span><span class="p">(</span><span class="n">template</span><span class="o">.</span><span class="n">Node</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">date_to_be_formatted</span><span class="p">,</span> <span class="n">format_string</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">date_to_be_formatted</span> <span class="o">=</span> <span class="n">template</span><span class="o">.</span><span class="n">Variable</span><span class="p">(</span><span class="n">date_to_be_formatted</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">format_string</span> <span class="o">=</span> <span class="n">format_string</span>

    <span class="k">def</span> <span class="nf">render</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">context</span><span class="p">):</span>
        <span class="k">try</span><span class="p">:</span>
            <span class="n">actual_date</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">date_to_be_formatted</span><span class="o">.</span><span class="n">resolve</span><span class="p">(</span><span class="n">context</span><span class="p">)</span>
            <span class="k">return</span> <span class="n">actual_date</span><span class="o">.</span><span class="n">strftime</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">format_string</span><span class="p">)</span>
        <span class="k">except</span> <span class="n">template</span><span class="o">.</span><span class="n">VariableDoesNotExist</span><span class="p">:</span>
            <span class="k">return</span> <span class="s">&#39;&#39;</span>
</pre></div>
</div>
<p>Variable resolution will throw a <tt class="docutils literal"><span class="pre">VariableDoesNotExist</span></tt> exception if it
cannot resolve the string passed to it in the current context of the page.</p>
</div>
<div class="section" id="s-simple-tags">
<span id="s-howto-custom-template-tags-simple-tags"></span><span id="simple-tags"></span><span id="howto-custom-template-tags-simple-tags"></span><h3>Simple tags<a class="headerlink" href="#simple-tags" title="Permalink to this headline">¶</a></h3>
<dl class="method">
<dt id="django.template.Library.simple_tag">
<tt class="descclassname">django.template.Library.</tt><tt class="descname">simple_tag</tt>()<a class="headerlink" href="#django.template.Library.simple_tag" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>Many template tags take a number of arguments &#8211; strings or template variables
&#8211; and return a string after doing some processing based solely on
the input arguments and some external information. For example, the
<tt class="docutils literal"><span class="pre">current_time</span></tt> tag we wrote above is of this variety: we give it a format
string, it returns the time as a string.</p>
<p>To ease the creation of these types of tags, Django provides a helper function,
<tt class="docutils literal"><span class="pre">simple_tag</span></tt>. This function, which is a method of
<tt class="docutils literal"><span class="pre">django.template.Library</span></tt>, takes a function that accepts any number of
arguments, wraps it in a <tt class="docutils literal"><span class="pre">render</span></tt> function and the other necessary bits
mentioned above and registers it with the template system.</p>
<p>Our earlier <tt class="docutils literal"><span class="pre">current_time</span></tt> function could thus be written like this:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">datetime</span>
<span class="kn">from</span> <span class="nn">django</span> <span class="kn">import</span> <span class="n">template</span>

<span class="n">register</span> <span class="o">=</span> <span class="n">template</span><span class="o">.</span><span class="n">Library</span><span class="p">()</span>

<span class="k">def</span> <span class="nf">current_time</span><span class="p">(</span><span class="n">format_string</span><span class="p">):</span>
    <span class="k">return</span> <span class="n">datetime</span><span class="o">.</span><span class="n">datetime</span><span class="o">.</span><span class="n">now</span><span class="p">()</span><span class="o">.</span><span class="n">strftime</span><span class="p">(</span><span class="n">format_string</span><span class="p">)</span>

<span class="n">register</span><span class="o">.</span><span class="n">simple_tag</span><span class="p">(</span><span class="n">current_time</span><span class="p">)</span>
</pre></div>
</div>
<p>The decorator syntax also works:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="nd">@register.simple_tag</span>
<span class="k">def</span> <span class="nf">current_time</span><span class="p">(</span><span class="n">format_string</span><span class="p">):</span>
    <span class="o">...</span>
</pre></div>
</div>
<p>A few things to note about the <tt class="docutils literal"><span class="pre">simple_tag</span></tt> helper function:</p>
<ul class="simple">
<li>Checking for the required number of arguments, etc., has already been
done by the time our function is called, so we don&#8217;t need to do that.</li>
<li>The quotes around the argument (if any) have already been stripped away,
so we just receive a plain string.</li>
<li>If the argument was a template variable, our function is passed the
current value of the variable, not the variable itself.</li>
</ul>
<p>If your template tag needs to access the current context, you can use the
<tt class="docutils literal"><span class="pre">takes_context</span></tt> argument when registering your tag:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="c"># The first argument *must* be called &quot;context&quot; here.</span>
<span class="k">def</span> <span class="nf">current_time</span><span class="p">(</span><span class="n">context</span><span class="p">,</span> <span class="n">format_string</span><span class="p">):</span>
    <span class="n">timezone</span> <span class="o">=</span> <span class="n">context</span><span class="p">[</span><span class="s">&#39;timezone&#39;</span><span class="p">]</span>
    <span class="k">return</span> <span class="n">your_get_current_time_method</span><span class="p">(</span><span class="n">timezone</span><span class="p">,</span> <span class="n">format_string</span><span class="p">)</span>

<span class="n">register</span><span class="o">.</span><span class="n">simple_tag</span><span class="p">(</span><span class="n">takes_context</span><span class="o">=</span><span class="bp">True</span><span class="p">)(</span><span class="n">current_time</span><span class="p">)</span>
</pre></div>
</div>
<p>Or, using decorator syntax:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="nd">@register.simple_tag</span><span class="p">(</span><span class="n">takes_context</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">current_time</span><span class="p">(</span><span class="n">context</span><span class="p">,</span> <span class="n">format_string</span><span class="p">):</span>
    <span class="n">timezone</span> <span class="o">=</span> <span class="n">context</span><span class="p">[</span><span class="s">&#39;timezone&#39;</span><span class="p">]</span>
    <span class="k">return</span> <span class="n">your_get_current_time_method</span><span class="p">(</span><span class="n">timezone</span><span class="p">,</span> <span class="n">format_string</span><span class="p">)</span>
</pre></div>
</div>
<p>For more information on how the <tt class="docutils literal"><span class="pre">takes_context</span></tt> option works, see the section
on <a class="reference internal" href="#howto-custom-template-tags-inclusion-tags"><em>inclusion tags</em></a>.</p>
<p>If you need to rename your tag, you can provide a custom name for it:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">register</span><span class="o">.</span><span class="n">simple_tag</span><span class="p">(</span><span class="k">lambda</span> <span class="n">x</span><span class="p">:</span> <span class="n">x</span> <span class="o">-</span> <span class="mi">1</span><span class="p">,</span> <span class="n">name</span><span class="o">=</span><span class="s">&#39;minusone&#39;</span><span class="p">)</span>

<span class="nd">@register.simple_tag</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s">&#39;minustwo&#39;</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">some_function</span><span class="p">(</span><span class="n">value</span><span class="p">):</span>
    <span class="k">return</span> <span class="n">value</span> <span class="o">-</span> <span class="mi">2</span>
</pre></div>
</div>
<p><tt class="docutils literal"><span class="pre">simple_tag</span></tt> functions may accept any number of positional or keyword
arguments. For example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="nd">@register.simple_tag</span>
<span class="k">def</span> <span class="nf">my_tag</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
    <span class="n">warning</span> <span class="o">=</span> <span class="n">kwargs</span><span class="p">[</span><span class="s">&#39;warning&#39;</span><span class="p">]</span>
    <span class="n">profile</span> <span class="o">=</span> <span class="n">kwargs</span><span class="p">[</span><span class="s">&#39;profile&#39;</span><span class="p">]</span>
    <span class="o">...</span>
    <span class="k">return</span> <span class="o">...</span>
</pre></div>
</div>
<p>Then in the template any number of arguments, separated by spaces, may be
passed to the template tag. Like in Python, the values for keyword arguments
are set using the equal sign (&#8220;<tt class="docutils literal"><span class="pre">=</span></tt>&#8221;) and must be provided after the
positional arguments. For example:</p>
<div class="highlight-html+django"><div class="highlight"><pre><span class="cp">{%</span> <span class="k">my_tag</span> <span class="m">123</span> <span class="s2">&quot;abcd&quot;</span> <span class="nv">book.title</span> <span class="nv">warning</span><span class="o">=</span><span class="nv">message</span><span class="o">|</span><span class="nf">lower</span> <span class="nv">profile</span><span class="o">=</span><span class="nv">user.profile</span> <span class="cp">%}</span>
</pre></div>
</div>
</div>
<div class="section" id="s-inclusion-tags">
<span id="s-howto-custom-template-tags-inclusion-tags"></span><span id="inclusion-tags"></span><span id="howto-custom-template-tags-inclusion-tags"></span><h3>Inclusion tags<a class="headerlink" href="#inclusion-tags" title="Permalink to this headline">¶</a></h3>
<p>Another common type of template tag is the type that displays some data by
rendering <em>another</em> template. For example, Django&#8217;s admin interface uses custom
template tags to display the buttons along the bottom of the &#8220;add/change&#8221; form
pages. Those buttons always look the same, but the link targets change
depending on the object being edited &#8211; so they&#8217;re a perfect case for using a
small template that is filled with details from the current object. (In the
admin&#8217;s case, this is the <tt class="docutils literal"><span class="pre">submit_row</span></tt> tag.)</p>
<p>These sorts of tags are called &#8220;inclusion tags&#8221;.</p>
<p>Writing inclusion tags is probably best demonstrated by example. Let&#8217;s write a
tag that outputs a list of choices for a given <tt class="docutils literal"><span class="pre">Poll</span></tt> object, such as was
created in the <a class="reference internal" href="../intro/tutorial01.html#creating-models"><em>tutorials</em></a>. We&#8217;ll use the tag like this:</p>
<div class="highlight-html+django"><div class="highlight"><pre><span class="cp">{%</span> <span class="k">show_results</span> <span class="nv">poll</span> <span class="cp">%}</span>
</pre></div>
</div>
<p>...and the output will be something like this:</p>
<div class="highlight-html"><div class="highlight"><pre><span class="nt">&lt;ul&gt;</span>
  <span class="nt">&lt;li&gt;</span>First choice<span class="nt">&lt;/li&gt;</span>
  <span class="nt">&lt;li&gt;</span>Second choice<span class="nt">&lt;/li&gt;</span>
  <span class="nt">&lt;li&gt;</span>Third choice<span class="nt">&lt;/li&gt;</span>
<span class="nt">&lt;/ul&gt;</span>
</pre></div>
</div>
<p>First, define the function that takes the argument and produces a dictionary of
data for the result. The important point here is we only need to return a
dictionary, not anything more complex. This will be used as a template context
for the template fragment. Example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">show_results</span><span class="p">(</span><span class="n">poll</span><span class="p">):</span>
    <span class="n">choices</span> <span class="o">=</span> <span class="n">poll</span><span class="o">.</span><span class="n">choice_set</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>
    <span class="k">return</span> <span class="p">{</span><span class="s">&#39;choices&#39;</span><span class="p">:</span> <span class="n">choices</span><span class="p">}</span>
</pre></div>
</div>
<p>Next, create the template used to render the tag&#8217;s output. This template is a
fixed feature of the tag: the tag writer specifies it, not the template
designer. Following our example, the template is very simple:</p>
<div class="highlight-html+django"><div class="highlight"><pre><span class="nt">&lt;ul&gt;</span>
<span class="cp">{%</span> <span class="k">for</span> <span class="nv">choice</span> <span class="k">in</span> <span class="nv">choices</span> <span class="cp">%}</span>
    <span class="nt">&lt;li&gt;</span> <span class="cp">{{</span> <span class="nv">choice</span> <span class="cp">}}</span> <span class="nt">&lt;/li&gt;</span>
<span class="cp">{%</span> <span class="k">endfor</span> <span class="cp">%}</span>
<span class="nt">&lt;/ul&gt;</span>
</pre></div>
</div>
<p>Now, create and register the inclusion tag by calling the <tt class="docutils literal"><span class="pre">inclusion_tag()</span></tt>
method on a <tt class="docutils literal"><span class="pre">Library</span></tt> object. Following our example, if the above template is
in a file called <tt class="docutils literal"><span class="pre">results.html</span></tt> in a directory that&#8217;s searched by the
template loader, we&#8217;d register the tag like this:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="c"># Here, register is a django.template.Library instance, as before</span>
<span class="n">register</span><span class="o">.</span><span class="n">inclusion_tag</span><span class="p">(</span><span class="s">&#39;results.html&#39;</span><span class="p">)(</span><span class="n">show_results</span><span class="p">)</span>
</pre></div>
</div>
<p>Alternatively it is possible to register the inclusion tag using a
<a class="reference internal" href="../ref/templates/api.html#django.template.Template" title="django.template.Template"><tt class="xref py py-class docutils literal"><span class="pre">django.template.Template</span></tt></a> instance:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">django.template.loader</span> <span class="kn">import</span> <span class="n">get_template</span>
<span class="n">t</span> <span class="o">=</span> <span class="n">get_template</span><span class="p">(</span><span class="s">&#39;results.html&#39;</span><span class="p">)</span>
<span class="n">register</span><span class="o">.</span><span class="n">inclusion_tag</span><span class="p">(</span><span class="n">t</span><span class="p">)(</span><span class="n">show_results</span><span class="p">)</span>
</pre></div>
</div>
<p>As always, decorator syntax works as well, so we could have written:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="nd">@register.inclusion_tag</span><span class="p">(</span><span class="s">&#39;results.html&#39;</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">show_results</span><span class="p">(</span><span class="n">poll</span><span class="p">):</span>
    <span class="o">...</span>
</pre></div>
</div>
<p>...when first creating the function.</p>
<p>Sometimes, your inclusion tags might require a large number of arguments,
making it a pain for template authors to pass in all the arguments and remember
their order. To solve this, Django provides a <tt class="docutils literal"><span class="pre">takes_context</span></tt> option for
inclusion tags. If you specify <tt class="docutils literal"><span class="pre">takes_context</span></tt> in creating a template tag,
the tag will have no required arguments, and the underlying Python function
will have one argument &#8211; the template context as of when the tag was called.</p>
<p>For example, say you&#8217;re writing an inclusion tag that will always be used in a
context that contains <tt class="docutils literal"><span class="pre">home_link</span></tt> and <tt class="docutils literal"><span class="pre">home_title</span></tt> variables that point
back to the main page. Here&#8217;s what the Python function would look like:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="c"># The first argument *must* be called &quot;context&quot; here.</span>
<span class="k">def</span> <span class="nf">jump_link</span><span class="p">(</span><span class="n">context</span><span class="p">):</span>
    <span class="k">return</span> <span class="p">{</span>
        <span class="s">&#39;link&#39;</span><span class="p">:</span> <span class="n">context</span><span class="p">[</span><span class="s">&#39;home_link&#39;</span><span class="p">],</span>
        <span class="s">&#39;title&#39;</span><span class="p">:</span> <span class="n">context</span><span class="p">[</span><span class="s">&#39;home_title&#39;</span><span class="p">],</span>
    <span class="p">}</span>
<span class="c"># Register the custom tag as an inclusion tag with takes_context=True.</span>
<span class="n">register</span><span class="o">.</span><span class="n">inclusion_tag</span><span class="p">(</span><span class="s">&#39;link.html&#39;</span><span class="p">,</span> <span class="n">takes_context</span><span class="o">=</span><span class="bp">True</span><span class="p">)(</span><span class="n">jump_link</span><span class="p">)</span>
</pre></div>
</div>
<p>(Note that the first parameter to the function <em>must</em> be called <tt class="docutils literal"><span class="pre">context</span></tt>.)</p>
<p>In that <tt class="docutils literal"><span class="pre">register.inclusion_tag()</span></tt> line, we specified <tt class="docutils literal"><span class="pre">takes_context=True</span></tt>
and the name of the template. Here&#8217;s what the template <tt class="docutils literal"><span class="pre">link.html</span></tt> might look
like:</p>
<div class="highlight-html+django"><div class="highlight"><pre>Jump directly to <span class="nt">&lt;a</span> <span class="na">href=</span><span class="s">&quot;</span><span class="cp">{{</span> <span class="nv">link</span> <span class="cp">}}</span><span class="s">&quot;</span><span class="nt">&gt;</span><span class="cp">{{</span> <span class="nv">title</span> <span class="cp">}}</span><span class="nt">&lt;/a&gt;</span>.
</pre></div>
</div>
<p>Then, any time you want to use that custom tag, load its library and call it
without any arguments, like so:</p>
<div class="highlight-html+django"><div class="highlight"><pre><span class="cp">{%</span> <span class="k">jump_link</span> <span class="cp">%}</span>
</pre></div>
</div>
<p>Note that when you&#8217;re using <tt class="docutils literal"><span class="pre">takes_context=True</span></tt>, there&#8217;s no need to pass
arguments to the template tag. It automatically gets access to the context.</p>
<p>The <tt class="docutils literal"><span class="pre">takes_context</span></tt> parameter defaults to <tt class="docutils literal"><span class="pre">False</span></tt>. When it&#8217;s set to
<tt class="docutils literal"><span class="pre">True</span></tt>, the tag is passed the context object, as in this example. That&#8217;s the
only difference between this case and the previous <tt class="docutils literal"><span class="pre">inclusion_tag</span></tt> example.</p>
<p><tt class="docutils literal"><span class="pre">inclusion_tag</span></tt> functions may accept any number of positional or keyword
arguments. For example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="nd">@register.inclusion_tag</span><span class="p">(</span><span class="s">&#39;my_template.html&#39;</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">my_tag</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
    <span class="n">warning</span> <span class="o">=</span> <span class="n">kwargs</span><span class="p">[</span><span class="s">&#39;warning&#39;</span><span class="p">]</span>
    <span class="n">profile</span> <span class="o">=</span> <span class="n">kwargs</span><span class="p">[</span><span class="s">&#39;profile&#39;</span><span class="p">]</span>
    <span class="o">...</span>
    <span class="k">return</span> <span class="o">...</span>
</pre></div>
</div>
<p>Then in the template any number of arguments, separated by spaces, may be
passed to the template tag. Like in Python, the values for keyword arguments
are set using the equal sign (&#8220;<tt class="docutils literal"><span class="pre">=</span></tt>&#8221;) and must be provided after the
positional arguments. For example:</p>
<div class="highlight-html+django"><div class="highlight"><pre><span class="cp">{%</span> <span class="k">my_tag</span> <span class="m">123</span> <span class="s2">&quot;abcd&quot;</span> <span class="nv">book.title</span> <span class="nv">warning</span><span class="o">=</span><span class="nv">message</span><span class="o">|</span><span class="nf">lower</span> <span class="nv">profile</span><span class="o">=</span><span class="nv">user.profile</span> <span class="cp">%}</span>
</pre></div>
</div>
</div>
<div class="section" id="s-setting-a-variable-in-the-context">
<span id="setting-a-variable-in-the-context"></span><h3>Setting a variable in the context<a class="headerlink" href="#setting-a-variable-in-the-context" title="Permalink to this headline">¶</a></h3>
<p>The above examples simply output a value. Generally, it&#8217;s more flexible if your
template tags set template variables instead of outputting values. That way,
template authors can reuse the values that your template tags create.</p>
<p>To set a variable in the context, just use dictionary assignment on the context
object in the <tt class="docutils literal"><span class="pre">render()</span></tt> method. Here&#8217;s an updated version of
<tt class="docutils literal"><span class="pre">CurrentTimeNode</span></tt> that sets a template variable <tt class="docutils literal"><span class="pre">current_time</span></tt> instead of
outputting it:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">datetime</span>
<span class="kn">from</span> <span class="nn">django</span> <span class="kn">import</span> <span class="n">template</span>

<span class="k">class</span> <span class="nc">CurrentTimeNode2</span><span class="p">(</span><span class="n">template</span><span class="o">.</span><span class="n">Node</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">format_string</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">format_string</span> <span class="o">=</span> <span class="n">format_string</span>
    <span class="k">def</span> <span class="nf">render</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">context</span><span class="p">):</span>
        <span class="n">context</span><span class="p">[</span><span class="s">&#39;current_time&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="n">datetime</span><span class="o">.</span><span class="n">datetime</span><span class="o">.</span><span class="n">now</span><span class="p">()</span><span class="o">.</span><span class="n">strftime</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">format_string</span><span class="p">)</span>
        <span class="k">return</span> <span class="s">&#39;&#39;</span>
</pre></div>
</div>
<p>Note that <tt class="docutils literal"><span class="pre">render()</span></tt> returns the empty string. <tt class="docutils literal"><span class="pre">render()</span></tt> should always
return string output. If all the template tag does is set a variable,
<tt class="docutils literal"><span class="pre">render()</span></tt> should return the empty string.</p>
<p>Here&#8217;s how you&#8217;d use this new version of the tag:</p>
<div class="highlight-html+django"><div class="highlight"><pre><span class="cp">{%</span> <span class="k">current_time</span> <span class="s2">&quot;%Y-%M-%d %I:%M %p&quot;</span> <span class="cp">%}</span><span class="nt">&lt;p&gt;</span>The time is <span class="cp">{{</span> <span class="nv">current_time</span> <span class="cp">}}</span>.<span class="nt">&lt;/p&gt;</span>
</pre></div>
</div>
<div class="admonition-variable-scope-in-context admonition">
<p class="first admonition-title">Variable scope in context</p>
<p class="last">Any variable set in the context will only be available in the same
<tt class="docutils literal"><span class="pre">block</span></tt> of the template in which it was assigned. This behavior is
intentional; it provides a scope for variables so that they don&#8217;t conflict
with context in other blocks.</p>
</div>
<p>But, there&#8217;s a problem with <tt class="docutils literal"><span class="pre">CurrentTimeNode2</span></tt>: The variable name
<tt class="docutils literal"><span class="pre">current_time</span></tt> is hard-coded. This means you&#8217;ll need to make sure your
template doesn&#8217;t use <tt class="docutils literal"><span class="pre">{{</span> <span class="pre">current_time</span> <span class="pre">}}</span></tt> anywhere else, because the
<tt class="docutils literal"><span class="pre">{%</span> <span class="pre">current_time</span> <span class="pre">%}</span></tt> will blindly overwrite that variable&#8217;s value. A cleaner
solution is to make the template tag specify the name of the output variable,
like so:</p>
<div class="highlight-html+django"><div class="highlight"><pre><span class="cp">{%</span> <span class="k">current_time</span> <span class="s2">&quot;%Y-%M-%d %I:%M %p&quot;</span> <span class="k">as</span> <span class="nv">my_current_time</span> <span class="cp">%}</span>
<span class="nt">&lt;p&gt;</span>The current time is <span class="cp">{{</span> <span class="nv">my_current_time</span> <span class="cp">}}</span>.<span class="nt">&lt;/p&gt;</span>
</pre></div>
</div>
<p>To do that, you&#8217;ll need to refactor both the compilation function and <tt class="docutils literal"><span class="pre">Node</span></tt>
class, like so:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">CurrentTimeNode3</span><span class="p">(</span><span class="n">template</span><span class="o">.</span><span class="n">Node</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">format_string</span><span class="p">,</span> <span class="n">var_name</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">format_string</span> <span class="o">=</span> <span class="n">format_string</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">var_name</span> <span class="o">=</span> <span class="n">var_name</span>
    <span class="k">def</span> <span class="nf">render</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">context</span><span class="p">):</span>
        <span class="n">context</span><span class="p">[</span><span class="bp">self</span><span class="o">.</span><span class="n">var_name</span><span class="p">]</span> <span class="o">=</span> <span class="n">datetime</span><span class="o">.</span><span class="n">datetime</span><span class="o">.</span><span class="n">now</span><span class="p">()</span><span class="o">.</span><span class="n">strftime</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">format_string</span><span class="p">)</span>
        <span class="k">return</span> <span class="s">&#39;&#39;</span>

<span class="kn">import</span> <span class="nn">re</span>
<span class="k">def</span> <span class="nf">do_current_time</span><span class="p">(</span><span class="n">parser</span><span class="p">,</span> <span class="n">token</span><span class="p">):</span>
    <span class="c"># This version uses a regular expression to parse tag contents.</span>
    <span class="k">try</span><span class="p">:</span>
        <span class="c"># Splitting by None == splitting by spaces.</span>
        <span class="n">tag_name</span><span class="p">,</span> <span class="n">arg</span> <span class="o">=</span> <span class="n">token</span><span class="o">.</span><span class="n">contents</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="bp">None</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span>
    <span class="k">except</span> <span class="ne">ValueError</span><span class="p">:</span>
        <span class="k">raise</span> <span class="n">template</span><span class="o">.</span><span class="n">TemplateSyntaxError</span><span class="p">(</span>
            <span class="s">&quot;</span><span class="si">%r</span><span class="s"> tag requires arguments&quot;</span> <span class="o">%</span> <span class="n">token</span><span class="o">.</span><span class="n">contents</span><span class="o">.</span><span class="n">split</span><span class="p">()[</span><span class="mi">0</span><span class="p">]</span>
        <span class="p">)</span>
    <span class="n">m</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="s">r&#39;(.*?) as (\w+)&#39;</span><span class="p">,</span> <span class="n">arg</span><span class="p">)</span>
    <span class="k">if</span> <span class="ow">not</span> <span class="n">m</span><span class="p">:</span>
        <span class="k">raise</span> <span class="n">template</span><span class="o">.</span><span class="n">TemplateSyntaxError</span><span class="p">(</span><span class="s">&quot;</span><span class="si">%r</span><span class="s"> tag had invalid arguments&quot;</span> <span class="o">%</span> <span class="n">tag_name</span><span class="p">)</span>
    <span class="n">format_string</span><span class="p">,</span> <span class="n">var_name</span> <span class="o">=</span> <span class="n">m</span><span class="o">.</span><span class="n">groups</span><span class="p">()</span>
    <span class="k">if</span> <span class="ow">not</span> <span class="p">(</span><span class="n">format_string</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">==</span> <span class="n">format_string</span><span class="p">[</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span> <span class="ow">and</span> <span class="n">format_string</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="ow">in</span> <span class="p">(</span><span class="s">&#39;&quot;&#39;</span><span class="p">,</span> <span class="s">&quot;&#39;&quot;</span><span class="p">)):</span>
        <span class="k">raise</span> <span class="n">template</span><span class="o">.</span><span class="n">TemplateSyntaxError</span><span class="p">(</span>
            <span class="s">&quot;</span><span class="si">%r</span><span class="s"> tag&#39;s argument should be in quotes&quot;</span> <span class="o">%</span> <span class="n">tag_name</span>
        <span class="p">)</span>
    <span class="k">return</span> <span class="n">CurrentTimeNode3</span><span class="p">(</span><span class="n">format_string</span><span class="p">[</span><span class="mi">1</span><span class="p">:</span><span class="o">-</span><span class="mi">1</span><span class="p">],</span> <span class="n">var_name</span><span class="p">)</span>
</pre></div>
</div>
<p>The difference here is that <tt class="docutils literal"><span class="pre">do_current_time()</span></tt> grabs the format string and
the variable name, passing both to <tt class="docutils literal"><span class="pre">CurrentTimeNode3</span></tt>.</p>
<p>Finally, if you only need to have a simple syntax for your custom
context-updating template tag, you might want to consider using an
<a class="reference internal" href="#howto-custom-template-tags-assignment-tags"><em>assignment tag</em></a>.</p>
</div>
<div class="section" id="s-assignment-tags">
<span id="s-howto-custom-template-tags-assignment-tags"></span><span id="assignment-tags"></span><span id="howto-custom-template-tags-assignment-tags"></span><h3>Assignment tags<a class="headerlink" href="#assignment-tags" title="Permalink to this headline">¶</a></h3>
<p>To ease the creation of tags setting a variable in the context, Django provides
a helper function, <tt class="docutils literal"><span class="pre">assignment_tag</span></tt>. This function works the same way as
<a class="reference internal" href="#howto-custom-template-tags-simple-tags"><em>simple_tag</em></a>, except that it
stores the tag&#8217;s result in a specified context variable instead of directly
outputting it.</p>
<p>Our earlier <tt class="docutils literal"><span class="pre">current_time</span></tt> function could thus be written like this:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">get_current_time</span><span class="p">(</span><span class="n">format_string</span><span class="p">):</span>
    <span class="k">return</span> <span class="n">datetime</span><span class="o">.</span><span class="n">datetime</span><span class="o">.</span><span class="n">now</span><span class="p">()</span><span class="o">.</span><span class="n">strftime</span><span class="p">(</span><span class="n">format_string</span><span class="p">)</span>

<span class="n">register</span><span class="o">.</span><span class="n">assignment_tag</span><span class="p">(</span><span class="n">get_current_time</span><span class="p">)</span>
</pre></div>
</div>
<p>The decorator syntax also works:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="nd">@register.assignment_tag</span>
<span class="k">def</span> <span class="nf">get_current_time</span><span class="p">(</span><span class="n">format_string</span><span class="p">):</span>
    <span class="o">...</span>
</pre></div>
</div>
<p>You may then store the result in a template variable using the <tt class="docutils literal"><span class="pre">as</span></tt> argument
followed by the variable name, and output it yourself where you see fit:</p>
<div class="highlight-html+django"><div class="highlight"><pre><span class="cp">{%</span> <span class="k">get_current_time</span> <span class="s2">&quot;%Y-%m-%d %I:%M %p&quot;</span> <span class="k">as</span> <span class="nv">the_time</span> <span class="cp">%}</span>
<span class="nt">&lt;p&gt;</span>The time is <span class="cp">{{</span> <span class="nv">the_time</span> <span class="cp">}}</span>.<span class="nt">&lt;/p&gt;</span>
</pre></div>
</div>
<p>If your template tag needs to access the current context, you can use the
<tt class="docutils literal"><span class="pre">takes_context</span></tt> argument when registering your tag:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="c"># The first argument *must* be called &quot;context&quot; here.</span>
<span class="k">def</span> <span class="nf">get_current_time</span><span class="p">(</span><span class="n">context</span><span class="p">,</span> <span class="n">format_string</span><span class="p">):</span>
    <span class="n">timezone</span> <span class="o">=</span> <span class="n">context</span><span class="p">[</span><span class="s">&#39;timezone&#39;</span><span class="p">]</span>
    <span class="k">return</span> <span class="n">your_get_current_time_method</span><span class="p">(</span><span class="n">timezone</span><span class="p">,</span> <span class="n">format_string</span><span class="p">)</span>

<span class="n">register</span><span class="o">.</span><span class="n">assignment_tag</span><span class="p">(</span><span class="n">takes_context</span><span class="o">=</span><span class="bp">True</span><span class="p">)(</span><span class="n">get_current_time</span><span class="p">)</span>
</pre></div>
</div>
<p>Or, using decorator syntax:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="nd">@register.assignment_tag</span><span class="p">(</span><span class="n">takes_context</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">get_current_time</span><span class="p">(</span><span class="n">context</span><span class="p">,</span> <span class="n">format_string</span><span class="p">):</span>
    <span class="n">timezone</span> <span class="o">=</span> <span class="n">context</span><span class="p">[</span><span class="s">&#39;timezone&#39;</span><span class="p">]</span>
    <span class="k">return</span> <span class="n">your_get_current_time_method</span><span class="p">(</span><span class="n">timezone</span><span class="p">,</span> <span class="n">format_string</span><span class="p">)</span>
</pre></div>
</div>
<p>For more information on how the <tt class="docutils literal"><span class="pre">takes_context</span></tt> option works, see the section
on <a class="reference internal" href="#howto-custom-template-tags-inclusion-tags"><em>inclusion tags</em></a>.</p>
<p><tt class="docutils literal"><span class="pre">assignment_tag</span></tt> functions may accept any number of positional or keyword
arguments. For example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="nd">@register.assignment_tag</span>
<span class="k">def</span> <span class="nf">my_tag</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
    <span class="n">warning</span> <span class="o">=</span> <span class="n">kwargs</span><span class="p">[</span><span class="s">&#39;warning&#39;</span><span class="p">]</span>
    <span class="n">profile</span> <span class="o">=</span> <span class="n">kwargs</span><span class="p">[</span><span class="s">&#39;profile&#39;</span><span class="p">]</span>
    <span class="o">...</span>
    <span class="k">return</span> <span class="o">...</span>
</pre></div>
</div>
<p>Then in the template any number of arguments, separated by spaces, may be
passed to the template tag. Like in Python, the values for keyword arguments
are set using the equal sign (&#8220;<tt class="docutils literal"><span class="pre">=</span></tt>&#8221;) and must be provided after the
positional arguments. For example:</p>
<div class="highlight-html+django"><div class="highlight"><pre><span class="cp">{%</span> <span class="k">my_tag</span> <span class="m">123</span> <span class="s2">&quot;abcd&quot;</span> <span class="nv">book.title</span> <span class="nv">warning</span><span class="o">=</span><span class="nv">message</span><span class="o">|</span><span class="nf">lower</span> <span class="nv">profile</span><span class="o">=</span><span class="nv">user.profile</span> <span class="k">as</span> <span class="nv">the_result</span> <span class="cp">%}</span>
</pre></div>
</div>
</div>
<div class="section" id="s-parsing-until-another-block-tag">
<span id="parsing-until-another-block-tag"></span><h3>Parsing until another block tag<a class="headerlink" href="#parsing-until-another-block-tag" title="Permalink to this headline">¶</a></h3>
<p>Template tags can work in tandem. For instance, the standard
<a class="reference internal" href="../ref/templates/builtins.html#std:templatetag-comment"><tt class="xref std std-ttag docutils literal"><span class="pre">{%</span> <span class="pre">comment</span> <span class="pre">%}</span></tt></a> tag hides everything until <tt class="docutils literal"><span class="pre">{%</span> <span class="pre">endcomment</span> <span class="pre">%}</span></tt>.
To create a template tag such as this, use <tt class="docutils literal"><span class="pre">parser.parse()</span></tt> in your
compilation function.</p>
<p>Here&#8217;s how a simplified <tt class="docutils literal"><span class="pre">{%</span> <span class="pre">comment</span> <span class="pre">%}</span></tt> tag might be implemented:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">do_comment</span><span class="p">(</span><span class="n">parser</span><span class="p">,</span> <span class="n">token</span><span class="p">):</span>
    <span class="n">nodelist</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">parse</span><span class="p">((</span><span class="s">&#39;endcomment&#39;</span><span class="p">,))</span>
    <span class="n">parser</span><span class="o">.</span><span class="n">delete_first_token</span><span class="p">()</span>
    <span class="k">return</span> <span class="n">CommentNode</span><span class="p">()</span>

<span class="k">class</span> <span class="nc">CommentNode</span><span class="p">(</span><span class="n">template</span><span class="o">.</span><span class="n">Node</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">render</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">context</span><span class="p">):</span>
        <span class="k">return</span> <span class="s">&#39;&#39;</span>
</pre></div>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The actual implementation of <a class="reference internal" href="../ref/templates/builtins.html#std:templatetag-comment"><tt class="xref std std-ttag docutils literal"><span class="pre">{%</span> <span class="pre">comment</span> <span class="pre">%}</span></tt></a> is slightly
different in that it allows broken template tags to appear between
<tt class="docutils literal"><span class="pre">{%</span> <span class="pre">comment</span> <span class="pre">%}</span></tt> and <tt class="docutils literal"><span class="pre">{%</span> <span class="pre">endcomment</span> <span class="pre">%}</span></tt>. It does so by calling
<tt class="docutils literal"><span class="pre">parser.skip_past('endcomment')</span></tt> instead of <tt class="docutils literal"><span class="pre">parser.parse(('endcomment',))</span></tt>
followed by <tt class="docutils literal"><span class="pre">parser.delete_first_token()</span></tt>, thus avoiding the generation of a
node list.</p>
</div>
<p><tt class="docutils literal"><span class="pre">parser.parse()</span></tt> takes a tuple of names of block tags &#8216;&#8217;to parse until&#8217;&#8216;. It
returns an instance of <tt class="docutils literal"><span class="pre">django.template.NodeList</span></tt>, which is a list of
all <tt class="docutils literal"><span class="pre">Node</span></tt> objects that the parser encountered &#8216;&#8217;before&#8217;&#8217; it encountered
any of the tags named in the tuple.</p>
<p>In <tt class="docutils literal"><span class="pre">&quot;nodelist</span> <span class="pre">=</span> <span class="pre">parser.parse(('endcomment',))&quot;</span></tt> in the above example,
<tt class="docutils literal"><span class="pre">nodelist</span></tt> is a list of all nodes between the <tt class="docutils literal"><span class="pre">{%</span> <span class="pre">comment</span> <span class="pre">%}</span></tt> and
<tt class="docutils literal"><span class="pre">{%</span> <span class="pre">endcomment</span> <span class="pre">%}</span></tt>, not counting <tt class="docutils literal"><span class="pre">{%</span> <span class="pre">comment</span> <span class="pre">%}</span></tt> and <tt class="docutils literal"><span class="pre">{%</span> <span class="pre">endcomment</span> <span class="pre">%}</span></tt>
themselves.</p>
<p>After <tt class="docutils literal"><span class="pre">parser.parse()</span></tt> is called, the parser hasn&#8217;t yet &#8220;consumed&#8221; the
<tt class="docutils literal"><span class="pre">{%</span> <span class="pre">endcomment</span> <span class="pre">%}</span></tt> tag, so the code needs to explicitly call
<tt class="docutils literal"><span class="pre">parser.delete_first_token()</span></tt>.</p>
<p><tt class="docutils literal"><span class="pre">CommentNode.render()</span></tt> simply returns an empty string. Anything between
<tt class="docutils literal"><span class="pre">{%</span> <span class="pre">comment</span> <span class="pre">%}</span></tt> and <tt class="docutils literal"><span class="pre">{%</span> <span class="pre">endcomment</span> <span class="pre">%}</span></tt> is ignored.</p>
</div>
<div class="section" id="s-parsing-until-another-block-tag-and-saving-contents">
<span id="parsing-until-another-block-tag-and-saving-contents"></span><h3>Parsing until another block tag, and saving contents<a class="headerlink" href="#parsing-until-another-block-tag-and-saving-contents" title="Permalink to this headline">¶</a></h3>
<p>In the previous example, <tt class="docutils literal"><span class="pre">do_comment()</span></tt> discarded everything between
<tt class="docutils literal"><span class="pre">{%</span> <span class="pre">comment</span> <span class="pre">%}</span></tt> and <tt class="docutils literal"><span class="pre">{%</span> <span class="pre">endcomment</span> <span class="pre">%}</span></tt>. Instead of doing that, it&#8217;s
possible to do something with the code between block tags.</p>
<p>For example, here&#8217;s a custom template tag, <tt class="docutils literal"><span class="pre">{%</span> <span class="pre">upper</span> <span class="pre">%}</span></tt>, that capitalizes
everything between itself and <tt class="docutils literal"><span class="pre">{%</span> <span class="pre">endupper</span> <span class="pre">%}</span></tt>.</p>
<p>Usage:</p>
<div class="highlight-html+django"><div class="highlight"><pre><span class="cp">{%</span> <span class="k">upper</span> <span class="cp">%}</span>This will appear in uppercase, <span class="cp">{{</span> <span class="nv">your_name</span> <span class="cp">}}</span>.<span class="cp">{%</span> <span class="k">endupper</span> <span class="cp">%}</span>
</pre></div>
</div>
<p>As in the previous example, we&#8217;ll use <tt class="docutils literal"><span class="pre">parser.parse()</span></tt>. But this time, we
pass the resulting <tt class="docutils literal"><span class="pre">nodelist</span></tt> to the <tt class="docutils literal"><span class="pre">Node</span></tt>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">do_upper</span><span class="p">(</span><span class="n">parser</span><span class="p">,</span> <span class="n">token</span><span class="p">):</span>
    <span class="n">nodelist</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">parse</span><span class="p">((</span><span class="s">&#39;endupper&#39;</span><span class="p">,))</span>
    <span class="n">parser</span><span class="o">.</span><span class="n">delete_first_token</span><span class="p">()</span>
    <span class="k">return</span> <span class="n">UpperNode</span><span class="p">(</span><span class="n">nodelist</span><span class="p">)</span>

<span class="k">class</span> <span class="nc">UpperNode</span><span class="p">(</span><span class="n">template</span><span class="o">.</span><span class="n">Node</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">nodelist</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">nodelist</span> <span class="o">=</span> <span class="n">nodelist</span>
    <span class="k">def</span> <span class="nf">render</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">context</span><span class="p">):</span>
        <span class="n">output</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">nodelist</span><span class="o">.</span><span class="n">render</span><span class="p">(</span><span class="n">context</span><span class="p">)</span>
        <span class="k">return</span> <span class="n">output</span><span class="o">.</span><span class="n">upper</span><span class="p">()</span>
</pre></div>
</div>
<p>The only new concept here is the <tt class="docutils literal"><span class="pre">self.nodelist.render(context)</span></tt> in
<tt class="docutils literal"><span class="pre">UpperNode.render()</span></tt>.</p>
<p>For more examples of complex rendering, see the source code for
<a class="reference internal" href="../ref/templates/builtins.html#std:templatetag-if"><tt class="xref std std-ttag docutils literal"><span class="pre">{%</span> <span class="pre">if</span> <span class="pre">%}</span></tt></a>, <a class="reference internal" href="../ref/templates/builtins.html#std:templatetag-for"><tt class="xref std std-ttag docutils literal"><span class="pre">{%</span> <span class="pre">for</span> <span class="pre">%}</span></tt></a>, <a class="reference internal" href="../ref/templates/builtins.html#std:templatetag-ifequal"><tt class="xref std std-ttag docutils literal"><span class="pre">{%</span> <span class="pre">ifequal</span> <span class="pre">%}</span></tt></a>
or <a class="reference internal" href="../ref/templates/builtins.html#std:templatetag-ifchanged"><tt class="xref std std-ttag docutils literal"><span class="pre">{%</span> <span class="pre">ifchanged</span> <span class="pre">%}</span></tt></a>. They live in
<tt class="docutils literal"><span class="pre">django/template/defaulttags.py</span></tt>.</p>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      
        
          <div class="yui-b" id="sidebar">
            
      <div class="sphinxsidebar">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">Custom template tags and filters</a><ul>
<li><a class="reference internal" href="#code-layout">Code layout</a></li>
<li><a class="reference internal" href="#writing-custom-template-filters">Writing custom template filters</a><ul>
<li><a class="reference internal" href="#registering-custom-filters">Registering custom filters</a></li>
<li><a class="reference internal" href="#template-filters-that-expect-strings">Template filters that expect strings</a></li>
<li><a class="reference internal" href="#filters-and-auto-escaping">Filters and auto-escaping</a></li>
<li><a class="reference internal" href="#filters-and-time-zones">Filters and time zones</a></li>
</ul>
</li>
<li><a class="reference internal" href="#writing-custom-template-tags">Writing custom template tags</a><ul>
<li><a class="reference internal" href="#a-quick-overview">A quick overview</a></li>
<li><a class="reference internal" href="#writing-the-compilation-function">Writing the compilation function</a></li>
<li><a class="reference internal" href="#writing-the-renderer">Writing the renderer</a></li>
<li><a class="reference internal" href="#auto-escaping-considerations">Auto-escaping considerations</a></li>
<li><a class="reference internal" href="#thread-safety-considerations">Thread-safety considerations</a></li>
<li><a class="reference internal" href="#registering-the-tag">Registering the tag</a></li>
<li><a class="reference internal" href="#passing-template-variables-to-the-tag">Passing template variables to the tag</a></li>
<li><a class="reference internal" href="#simple-tags">Simple tags</a></li>
<li><a class="reference internal" href="#inclusion-tags">Inclusion tags</a></li>
<li><a class="reference internal" href="#setting-a-variable-in-the-context">Setting a variable in the context</a></li>
<li><a class="reference internal" href="#assignment-tags">Assignment tags</a></li>
<li><a class="reference internal" href="#parsing-until-another-block-tag">Parsing until another block tag</a></li>
<li><a class="reference internal" href="#parsing-until-another-block-tag-and-saving-contents">Parsing until another block tag, and saving contents</a></li>
</ul>
</li>
</ul>
</li>
</ul>

  <h3>Browse</h3>
  <ul>
    
      <li>Prev: <a href="custom-lookups.html">Custom Lookups</a></li>
    
    
      <li>Next: <a href="custom-file-storage.html">Writing a custom storage system</a></li>
    
  </ul>
  <h3>You are here:</h3>
  <ul>
      <li>
        <a href="../index.html">Django 1.7.8.dev20150401230226 documentation</a>
        
          <ul><li><a href="index.html">&#8220;How-to&#8221; guides</a>
        
        <ul><li>Custom template tags and filters</li></ul>
        </li></ul>
      </li>
  </ul>

  <h3>This Page</h3>
  <ul class="this-page-menu">
    <li><a href="../_sources/howto/custom-template-tags.txt"
           rel="nofollow">Show Source</a></li>
  </ul>
<div id="searchbox" style="display: none">
  <h3>Quick search</h3>
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    <p class="searchtip" style="font-size: 90%">
    Enter search terms or a module, class or function name.
    </p>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
              <h3>Last update:</h3>
              <p class="topless">Apr 02, 2015</p>
          </div>
        
      
    </div>

    <div id="ft">
      <div class="nav">
    &laquo; <a href="custom-lookups.html" title="Custom Lookups">previous</a>
     |
    <a href="index.html" title="&amp;#8220;How-to&amp;#8221; guides" accesskey="U">up</a>
   |
    <a href="custom-file-storage.html" title="Writing a custom storage system">next</a> &raquo;</div>
    </div>
  </div>

      <div class="clearer"></div>
    </div>
  </body>
</html>